Как из vba открыть блокнот
Перейти к содержимому

Как из vba открыть блокнот

  • автор:

Метод CreateTextFile

Создает указанное имя файла и возвращает объект TextStream , который можно использовать для чтения или записи в файл.

Синтаксис

object. CreateTextFile (имя файла, [ перезапись, [ юникод ]])

Синтаксис метода CreateTextFile состоит из следующих частей:

Part Описание
object Обязательно. Всегда имя объекта FileSystemObject или Folder .
Имени файла Обязательно. Строковое выражение, определяющее файл, который требуется создать.
Перезаписать Необязательный параметр. Значение Boolean, указывающее, требуется ли перезаписывать существующий файл. Имеет значение True, если файл можно перезаписать, и False в противном случае. Если этот параметр опущен, существующие файлы могут быть перезаписаны.
Юникода Необязательный параметр. Значение Boolean, указывающее, будет ли файл создан в формате Юникод или ASCII. Значение True, если файл будет создан в формате Юникод, значение False, если требуется создать ASCII-файл. Если этот элемент опущен, создается ASCII-файл.

Замечания

В следующем коде показано, как использовать метод CreateTextFile для создания и открытия текстового файла. Если аргумент overwrite имеет значение False или не задан, то значение атрибута filename, указывающее на существующий файл, приведет к возникновению ошибки.

Sub CreateAfile Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("c:\testfile.txt", True) a.WriteLine("This is a test.") a.Close End Sub 

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Обратная связь

Были ли сведения на этой странице полезными?

Обратная связь

Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделе https://aka.ms/ContentUserFeedback.

Отправить и просмотреть отзыв по

Open and Write to Notepad from excel VBA

I need to open notepad and write my results from my macro to it. I want to open notepad and write to it, and have the user review and if he or she wants to save it then save it wherever they like. Instead of writing to it and saving on the computer all in the code. Thanks

8,206 8 8 gold badges 49 49 silver badges 63 63 bronze badges
asked Jul 1, 2015 at 15:09
203 2 2 gold badges 5 5 silver badges 10 10 bronze badges
I would recommend browsing this: mrexcel.com/forum/excel-questions/…
Jul 1, 2015 at 15:15

Also, this is not a forum for asking someone to write code for you. You should provide the code that you have tried and the exact problem you are having with the code and someone will gladly help you pinpoint the issue and resolve it.

Jul 1, 2015 at 15:16

@OpiesDad I think the question is focused enough on a particular issue he is facing for which he has no clue.

Jul 1, 2015 at 15:22

I have the code but I want to modify it so I’m not the one saving it one someone else’s computer. I want them to be able to chose to save it or not. The code is very similar to the other posts so I didn’t post it. My problem is not with fixing my code but rather the syntax on how to just open and view the file without saving it.

Jul 1, 2015 at 15:41

2 Answers 2

Use the following code to open notepad and type into it:

Dim myApp As String myApp = Shell("Notepad", vbNormalFocus) SendKeys "test", True 

answered Jul 1, 2015 at 15:17
10.9k 2 2 gold badges 27 27 silver badges 43 43 bronze badges

Similar to Tarik’s answer, I would probably use something like the following:

In a class module called NotepadManager: Option Explicit Private Const CAPTION$ = "Notepad" Private MHwnd As Long 'based on code lifted from: 'http://www.pbdr.com/vbtips/api/FindCloseAPI.htm Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _ (ByVal lpClassName As Any, ByVal lpWindowName As Any) As Long Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _ (ByVal hWnd As Long, ByVal lpString As String, _ ByVal aint As Long) As Long Private Declare Function GetWindow Lib "user32" _ (ByVal hWnd As Long, ByVal wCmd As Long) As Long Private Declare Function EnumWindows Lib "user32" _ (ByVal wndenmprc As Long, ByVal lParam As Long) As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _ lParam As Any) As Long Private Declare Function SetForegroundWindow Lib "user32" ( _ ByVal hWnd As Long) As Long Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const WM_CLOSE = &H10 Private Const GW_HWNDFIRST = 0 Private Const GW_HWNDLAST = 1 Private Const GW_HWNDNEXT = 2 Private Const GW_HWNDPREV = 3 Private Const GW_OWNER = 4 Private Const GW_CHILD = 5 Private Const GW_MAX = 5 Private mstrTarget As String Private mblnSuccess As Boolean Public Sub writeMessageToNotepad(ByRef message As String) focusNotepad Sleep 2000 SendKeys (message) End Sub Public Sub startNotepad() Dim ret ret = Shell("notepad", vbNormalFocus) End Sub Public Sub focusNotepad() If MHwnd = 0 Then MHwnd = hwndFindWindow(CAPTION$) End If If MHwnd = 0 Then MsgBox "Error: Cannot find notepad." Debug.Print SetForegroundWindow(MHwnd) End Sub Private Function hwndFindWindow(strApplicationTitle As String) As Long Dim hWndTmp As Long Dim nRet As Integer Dim TitleTmp As String Dim TitlePart As String Dim MyWholeTitle As String Dim mCounter As Long Dim hWndOver As Integer Dim sClassName As String * 100 hwndFindWindow = False TitlePart = UCase$(strApplicationTitle) 'loop through all the open windows hWndTmp = FindWindow(0&, 0&) Do Until hWndTmp = 0 TitleTmp = Space$(256) nRet = GetWindowText(hWndTmp, TitleTmp, Len(TitleTmp)) If nRet Then 'retrieve window title TitleTmp = UCase$(VBA.Left$(TitleTmp, nRet)) 'compare window title & strApplicationTitle If InStr(TitleTmp, TitlePart) Then hwndFindWindow = FindWindow(vbEmpty, TitleTmp) Exit Do End If End If hWndTmp = GetWindow(hWndTmp, GW_HWNDNEXT) mCounter = mCounter + 1 Loop End Function Private Function EnumCallback(ByVal app_hWnd As Long, _ ByVal param As Long) As Long Dim buf As String * 256 Dim title As String Dim length As Long ' Checks a returned task to determine if App should be closed ' get window's title. length = GetWindowText(app_hWnd, buf, Len(buf)) title = Left$(buf, length) ' determine if target window. If InStr(UCase(title), UCase(mstrTarget)) <> 0 Then ' Kill window. SendMessage app_hWnd, WM_CLOSE, 0, 0 mblnSuccess = True End If ' continue searching. EnumCallback = 1 End Function 

And in a normal module:

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Sub test() Dim m As New NotepadManager m.startNotepad m.focusNotepad Sleep 2000 m.writeMessageToNotepad "My message" Debug.Print "done" End Sub 

However, I’ve often found that ensuring you have window focus is the most difficult thing when you have a user interacting with the machine at the time.

Файловые функции VBA

    CurDir() — функция, которая возвращает путь к каталогу(для указанного диска), в котором по умолчанию будут сохраняться файлы:

Dim sCurDir As String sCurDir = CurDir("D")

Dim sCurDir As String sCurDir = CurDir(«D»)

    Input() — открывает текстовый файл на чтение. Т.е. таким методом можно открыть файл и вытянуть из него данные. Например, чтобы считать информацию из файла C:Text1.txt и вывести ее в окно Immediate можно применить такой код:
Dim MyChar Open "C:\Text1.txt" For Input As #1 'Открываем файл функцией Open() на чтение(Input) Do While Not EOF(1) 'пока файл не кончился ' Получаем по одному символу и добавляем его к предыдущим MyChar = MyChar & Input(1, #1) Loop Close #1 ' Закрываем файл 'Выводим его содержание в окно Immediate '(отобразить Immediate: Ctrl+G в окне редактора VBA) Debug.Print MyChar 'или в MsgBox MsgBox MyChar, vbInformation, "www.excel-vba.ru"

Dim MyChar Open «C:\Text1.txt» For Input As #1 ‘Открываем файл функцией Open() на чтение(Input) Do While Not EOF(1) ‘пока файл не кончился ‘ Получаем по одному символу и добавляем его к предыдущим MyChar = MyChar & Input(1, #1) Loop Close #1 ‘ Закрываем файл ‘Выводим его содержание в окно Immediate ‘(отобразить Immediate: Ctrl+G в окне редактора VBA) Debug.Print MyChar ‘или в MsgBox MsgBox MyChar, vbInformation, «www.excel-vba.ru»

Sub SelectionToTxt() Dim s As String, rc As Range Dim ff 'запоминаем все значения из выделенной строки в строку For Each rc In Selection If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки s = rc.Value Else 'если уже записано - добавляем через TAB s = s & vbTab & rc.Value End If Next ff = FreeFile 'Открываем текстовый файл 'если файла нет - он будет создан Open "C:\Text1.txt" For Output As #ff 'записываем значение строки в файл Print #ff, s Close #ff ' Закрываем файл End Sub

Sub SelectionToTxt() Dim s As String, rc As Range Dim ff ‘запоминаем все значения из выделенной строки в строку For Each rc In Selection If s = «» Then ‘если пока ничего не записали — присваиваем только значение ячейки s = rc.Value Else ‘если уже записано — добавляем через TAB s = s & vbTab & rc.Value End If Next ff = FreeFile ‘Открываем текстовый файл ‘если файла нет — он будет создан Open «C:\Text1.txt» For Output As #ff ‘записываем значение строки в файл Print #ff, s Close #ff ‘ Закрываем файл End Sub

Sub SelectionToTxt_Add() Dim s As String, rc As Range Dim ff 'запоминаем все значения из выделенной строки в строку For Each rc In Selection If s = "" Then 'если пока ничего не записали - присваиваем только значение ячейки s = rc.Value Else 'если уже записано - добавляем через TAB s = s & vbTab & rc.Value End If Next ff = FreeFile 'Открываем текстовый файл 'если файла нет - он будет создан Open "C:\Text1.txt" For Append As #ff 'записываем значение строки в файл Print #ff, s Close #ff ' Закрываем файл End Sub

Sub SelectionToTxt_Add() Dim s As String, rc As Range Dim ff ‘запоминаем все значения из выделенной строки в строку For Each rc In Selection If s = «» Then ‘если пока ничего не записали — присваиваем только значение ячейки s = rc.Value Else ‘если уже записано — добавляем через TAB s = s & vbTab & rc.Value End If Next ff = FreeFile ‘Открываем текстовый файл ‘если файла нет — он будет создан Open «C:\Text1.txt» For Append As #ff ‘записываем значение строки в файл Print #ff, s Close #ff ‘ Закрываем файл End Sub

sFileDateTime = FileDateTime("C:\Text1.txt")

sFileDateTime = FileDateTime(«C:\Text1.txt»)

MsgBox FileLen("C:\Text1.txt") & " bites", vbInformation, "www.excel-vba.ru"

Open a file with notepad through VBA

And, when you fix that code, it will let you read the contents of that file, supposedly created in Notepad, not launch Notepad itself.

Mar 2, 2018 at 16:43
I have defined it as Dim myOFSO As Object
Mar 2, 2018 at 16:45

@GSerg — I need to launch the notepad file and read the contents of that file as well. What line should I add to launch that particular notepad file. Thanks in advance.

Mar 2, 2018 at 16:46

And how did you assign it? I get the error 424 only if I do not use Option Explicit. So, please tell, what you really did!

Mar 2, 2018 at 16:46

5 Answers 5

Could just call a shell command to execute notepad.exe with the file path.

returnvalue = Shell("notepad.exe " & strfilename, vbNormalFocus) 

answered Mar 2, 2018 at 16:44
2,594 4 4 gold badges 17 17 silver badges 26 26 bronze badges

Thanks for the help. I tried using shell command earlier, but it wasn’t working as I didn’t mentioned vbNormalFocus. Now it working fine and I am able to launch the notepad. I hope it will read the contents of the notepad as well?

Mar 2, 2018 at 16:50

This opens Notepad with the file contents displayed. But it also generates an error: «Object variable or With block variable not set». How did you initialize the object?

Apr 5, 2019 at 18:12

This should be the only accepted answer. With all due respect to the others, the question asked how to open notepad NOT how to open the default program. I am generating an .sql file. I don’t WANT to open it with the default application I want to use notepad. This is the only response that works and the only one that answers the question.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *