1

我有以下代码来获取当前打开的 excel 文件的标题,此代码工作正常。如果标题更改,我每 10 秒使用一次计时器,然后在 list1 中添加新标题。

所以问题是否有任何方法或事件来检测标题是否更改然后我的代码工作,否则它不起作用不检查。计时器每 10 秒检查一次,如果我运行此代码,我的电脑会运行缓慢

Private Const GW_HWNDNEXT = 2

Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Long, _
ByVal wCmd As Long) As Long

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

Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Sub ListWins(Optional Title = "*", Optional Class = "*")
    Dim hWndThis As Long

    hWndThis = FindWindow(vbNullString, vbNullString)

    While hWndThis
        Dim sTitle As String, sClass As String
        sTitle = Space$(255)
        sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))

        sClass = Space$(255)
        sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))

        If sTitle Like Title And sClass Like Class Then
            Debug.Print sTitle, sClass
            List1.AddItem (sTitle)
        End If

        hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
    Wend
End Sub

Private Sub Timer1_Timer()
    ListWins "*.xls*"
End Sub
4

2 回答 2

0

您可以使用 Excel COM API 来执行此操作。不幸的是,没有办法获得 Excel 窗口标题 - 但您可以通过附加“ - Microsoft Excel”轻松制作它。如果需要完整路径,请使用 FullName 属性。

Option Explicit

Private WithEvents m_oApplication               As Excel.Application

Private Sub Command_Click()

    ' Get a reference to the FIRST instance of the Excel application.
    Set m_oApplication = GetObject(, "Excel.Application")

End Sub

Private Sub m_oApplication_NewWorkbook(ByVal Wb As Excel.Workbook)
    List1.AddItem Wb.Name
End Sub

Private Sub m_oApplication_WorkbookAfterSave(ByVal Wb As Excel.Workbook, ByVal Success As Boolean)
    'List1.AddItem "WorkbookAfterSave: " & Wb.FullName
    List1.AddItem Wb.Name
End Sub

Private Sub m_oApplication_WorkbookOpen(ByVal Wb As Excel.Workbook)
    List1.AddItem Wb.Name
End Sub
于 2013-09-16T10:19:23.773 回答
0

答案是No。AFAIK,不,在 vb6 中没有这样的事件会捕获 Excel 或任何其他窗口中的标题更改。不幸的是,10 秒计时器可能并不好。如果标题每 2 秒更改一次会发生什么?它不会检索所有标题

但是,请尝试不使用 Timer Control 的替代方案。看看你的电脑是否仍然很慢...

Sub Sample()
    '
    ' ~~> Rest of your code
    '

    Wait 2 '<~~ Wait for 2 seconds

    '
    ' ~~> Rest of your code
    '
End Sub

Private Sub Wait(ByVal nSec As Long)
    nSec = nSec + Timer
    While nSec > Timer
        DoEvents
    Wend
End Sub
于 2013-09-15T14:10:11.557 回答