读取激活程序的VBA代码

读取激活程序的VBA代码,vba,excel,Vba,Excel,我希望这个宏能够持续记录当前活动程序的名称。我有一个用户窗体,它运行一个计时器用户,一个每秒都会自动调用的宏。我希望它在同一宏中记录活动窗口的名称,如果与姓氏不同,则将其附加到描述性字符串中 我最初使用Active window.caption只是为了了解它不适用于其他程序,如chrome、word或Outlook,但下面是我的一段代码 If ActiveApp <> ActiveWindow.Caption Then 'look at active progra

我希望这个宏能够持续记录当前活动程序的名称。我有一个用户窗体,它运行一个计时器用户,一个每秒都会自动调用的宏。我希望它在同一宏中记录活动窗口的名称,如果与姓氏不同,则将其附加到描述性字符串中

我最初使用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调用

在办公网站上应该可以帮助你

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 sub应该将活动窗口的标题打印到调试控制台