记事本是另外一个程序自动打开的,我事先并不知道该文本的名称和路径,所以不可以用Open ...for...语句来操作。我是想通过VBA发现系统打开了一个记事本之后,将里面的内容复制到Excel中,然后将该记事本关闭。请教各位高手该如何写代码,谢谢!

解决方案 »

  1.   

    http://www.autohotkey.com
      

  2.   

    vb还是vba?excel ,vba的话不能关闭外部程序vb的话,提供下思路定时搜索记事本的窗体,然后getwindowstext,接着打开excel输入数据,然后关闭记事本.
      

  3.   

    Option ExplicitPrivate Const WM_DESTROY        As Long = &H2
    Private Const WM_NCDESTROY      As Long = &H82Private Declare Function DestroyWindow Lib "user32.dll" (ByVal hwnd As Long) As Long
    Private Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Boolean
    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 GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
    Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
    Private Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As LongPublic Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
        Dim lLength     As Long
        Dim sText       As String
        Dim hEdit       As Long
        
        '获取窗体标题,判断是否为记事本'
        lLength = GetWindowTextLength(hwnd)
        If lLength = 0 Then GoTo NextWindow
        
        sText = Space(lLength)
        GetWindowText hwnd, sText, lLength + 1
        
        If Not (sText Like "* - 记事本") Then GoTo NextWindow
        
        Debug.Print Hex(hwnd) & " : " & sText
        
        '取得编辑框文本'
        hEdit = FindWindowEx(hwnd, 0&, "Edit", vbNullString)
        
        lLength = GetWindowTextLength(hEdit)
        If lLength = 0 Then
            sText = vbNullString
        Else
            sText = Space(lLength)
            GetWindowText hEdit, sText, lLength + 1
        End If
        
        Debug.Print Hex(hEdit) & " : " & sText    '关闭记事本'
        PostMessage hwnd, WM_DESTROY, 0&, 0&
        PostMessage hwnd, WM_NCDESTROY, 0&, 0&
        
    StopEnum:
        EnumWindowsProc = False
        Exit Function
    NextWindow:
        EnumWindowsProc = True
    End FunctionPublic Sub f()
        EnumWindows AddressOf EnumWindowsProc, ByVal 0&
    End Sub
    运行上面的宏 f 即可。
    EnumWindowsProc 里面取得的记事本内容(sText),你可以直接输出到 Excel 中。
      

  4.   

    可以用我几年前写的一个类clswindow,非常方便。
    clswindow介绍:http://blog.csdn.net/sysdzw/article/details/9083313下面代码测试通过。
    Sub 按钮1_Click()
        Dim w As New clsWindow
        Range("A1") = w.GetWindowByTitleEx("记事本", 1).GetElementTextByClassName("edit")
        w.CloseWindow'关闭记事本窗口
    End Sub
    如果一个程序有多个窗口的话关闭用w.CloseApp
    窗口关闭还可以用淡出特效:w.FadeOut , True '慢慢消失最后关闭窗口
      

  5.   

    上面代码的测试文件已上传,下载地址:http://download.csdn.net/detail/sysdzw/9401598