用于读取事件程序的 VBA 代码

标签 vba excel

我的希望是让这个宏不断记录当前事件程序的名称。我有一个用户窗体,它运行一个计时器用户宏,该宏每秒都会调用自己。我希望它在同一宏中记录事件窗口的名称,并将其附加到描述性字符串(如果与姓氏不同)。

我最初使用“Active window.caption”只是为了了解它不适用于其他程序(例如 chrome、word 或 Outlook),但下面是我的一大块代码。

If ActiveApp <> ActiveWindow.Caption Then           'look at active program for name
            ActiveApp = ActiveWindow.Caption                'if the last name is not the same as the current
            aapp2 = ThisWorkbook.Sheets("bts").Range("b13").Value & "|" & ActiveApp & ": " & Format(dteElapsed, "hh:mm:ss")
            'updates the descriptive string
            ThisWorkbook.Sheets("bts").Range("b13").Value = aapp2
        End If

整个宏:

Sub timeloop()


If ThisWorkbook.Sheets("BTS").Range("b7").Value = "" Then 'the location on theworksheet that time is stored
    ThisWorkbook.Sheets("BTS").Range("b7").Value = Time '
    ThisWorkbook.Sheets("BTS").Range("b12").Value = Date
    End If



    dteStart = ThisWorkbook.Sheets("BTS").Range("b7").Value
    dteFinish = Time
    DoEvents
    dteElapsed = dteFinish - dteStart
    If Not booldead = True Then 'See if form has died

       TimeRun.Label1 = Format(dteElapsed, "hh:mm:ss")
        If ActiveApp <> ActiveWindow.Caption Then           'look at active program for name
            ActiveApp = ActiveWindow.Caption                'if the last name is not the same as the current
            aapp2 = ThisWorkbook.Sheets("bts").Range("b13").Value & "|" & ActiveApp & ": " & Format(dteElapsed, "hh:mm:ss")
            'updates the descriptive string
            ThisWorkbook.Sheets("bts").Range("b13").Value = aapp2
        End If


    Else
        Exit Sub
    End If
    Alerttime = Now + TimeValue("00:00:01")
Application.OnTime Alerttime, "TimeLoop"
End Sub

最佳答案

要获取事件应用程序/窗口的名称,您需要使用 API 调用。

This Question办公网站上的内容应该对您有帮助。

Public Declare Function GetForegroundWindow Lib "user32" _
    Alias "GetForegroundWindow" () As Long
Public Declare Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (ByVal hwnd As Long, _
    ByVal lpString As String, ByVal cch As Long) As Long

Sub AAA()
    Dim WinText As String
    Dim HWnd As Long
    Dim L As Long
    HWnd = GetForegroundWindow()
    WinText = String(255, vbNullChar)
    L = GetWindowText(HWnd, WinText, 255)
    WinText = Left(WinText, InStr(1, WinText, vbNullChar) - 1)
    Debug.Print L, WinText
End Sub

运行 AAA 子程序应将事件窗口的标题打印到调试控制台。

关于用于读取事件程序的 VBA 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747361/

相关文章:

excel - 如果下面有另一个表,是否可以一次在表中插入多行?

c# - 将 MySql 数据库导出到文件中

python - Python 中的 Excel VBA 格式条件

excel - 删除名称中包含相同符号的选项卡

excel - 将 2nd 维度从 2D 变体写入 Range,无需在 VBA 中循环

excel - 具有多个条件的四个日期的平均值

vba - ListView 列顺序的控制

python - 如何使用数据框创建不确定长度的Excel电子表格?

Excel VBA 范围值有时无法进行比较检查

excel - 将预测值与实际值匹配