在新记事本中写入文本

时间:2015-11-11 03:29:04

标签: excel vba excel-vba

是否有人可以帮我将单元格值写入记事本的新实例?

这是我尝试过的代码:

Sub a()
    Dim nt As String
    nt = Shell("notepad.exe", vbNormalFocus)
    Print #1, ActiveSheet.Cells(1, 1).Value
    Close #1
End Sub

1 个答案:

答案 0 :(得分:5)

多年前我在vbforums.com上回答了类似的问题,但是找不到它,所以我很快就为你重新编写了这个问题。我已对代码进行了评论,因此您无需理解它。

和你我一样,我们都有名字,类似的窗口有“句柄”(hWnd),类等。一旦你知道hWnd是什么,就更容易与那个窗口进行交互。 Findwindow API使用类名来查找特定窗口的hWnd。阅读其余的API Here

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
ByVal lpsz2 As String) 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 Const WM_SETTEXT = &HC

Private Sub Command1_Click()
    Dim Ret As Long, ChildRet As Long
    Dim sString As String

    '~~> This is the value from the cell which
    '~~> you want to send to notepad
    sString = Range("A1").Value

    '~~> Start Notepad
    Ret = Shell("notepad.exe", vbNormalFocus)

    '~~> Wait for it to load
    DoEvents

    '~~> Find notepad
    Ret = FindWindow(vbNullString, "Untitled - Notepad")

    '~~> Check if found
    If Ret = 0 Then
        MsgBox "Cannot find Notepad Window"
        Exit Sub
    End If

    '~~> Find the "Edit Window" which is a child window of Notepad window
    ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString)

    '~~> Send the message
    SendMessage ChildRet, WM_SETTEXT, 0, ByVal sString
End Sub

要获取windows的类名,我通常使用Spy ++或uuSpy。看到这是我如何得到类名"编辑"使用Spy ++的记事本

enter image description here