Timer on Excel VBA - vba

Dim StartTime As Date
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("H6").Value = Time - StartTimer
End Sub
Public Sub sheet()
Sheets("1").Activate
StartTime = Time
Call Module1.StartTimer
End Sub
I would like to write a code which show timer how much time user working on the Worksheet.
Example there is a start button in sheet1 when user click on start button then it will active sheet2 then a timer will run in cell A1. if the timer is 30 min then the workbook save & close.

Try this
Create Button and assign to the following macro
Option Explicit
Sub NewTimer()
Dim Start As Single
Dim Cell As Range
Dim CountDown As Date
'// Store timer as variable
Start = Timer
'// Format cell A1 to 24Hrs eg: 00:00:00
With Range("A1")
.NumberFormat = "HH:MM:SS;#"
End With
Set Cell = Sheet1.Range("A1")
'// This is the starting value. 30 Second
CountDown = TimeValue("00:00:30")
'// Set cell to the starting value
Cell.Value = CountDown
'Keep looping until A1 hits zero or
Do While Cell.Value > 0
'Update the cell. Timer - Starting number is seconds
Cell.Value = CountDown - TimeSerial(0, 0, Timer - Start)
DoEvents
Loop
ThisWorkbook.Save
ThisWorkbook.Close
Application.Quit
End Sub
Thanks to Dick Kusleika See Example

Related

How to perform Prnt Screen and save it into a specific folder

I found a code to perform a Prnt Screen without using Sendkeys method:
Option Explicit
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal _
bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Const VK_SNAPSHOT = &H2C
Sub PrintScreen()
keybd_event VK_SNAPSHOT, 1, 0, 0
End Sub
I haven't tried yet if it works properly (if not, I will use Sendkeys), but I'm wondering if there's a way to Prnt Screen and save it as .pdf/.jpg (doesn't matter) into a specific folder. All the print screen are about Internet Explorer pages.
The code you have only simulates "pressing" the PrtScrn key, but not "releasing" it. Add the second line here like this:
Option Explicit
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal _
bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Const VK_SNAPSHOT = &H2C
Private Const KEYEVENTF_KEYUP = 2
Sub PrintScreen()
keybd_event VK_SNAPSHOT, 1, 0, 0 'Key Down
keybd_event VK_SNAPSHOT, 1, KEYEVENTF_KEYUP , 0 'Key Up
End Sub
You can then paste the screenshot to a Worksheet and export it as PDF
Sub SaveAsPDF()
Const FILE_PATH as String = "C:\Temp\"
PrintScreen 'Take a screenshot
With Sheet1
.Paste 'Paste it to Sheet1
.ExportAsFixedFormat xlTypePDF, FILE_PATH & "Screenshot File.pdf" 'Export Sheet1 to PDF
End With
End Sub
I found the code below in an another thread which is working as per your requirement.
I tested it and it is taking snapshot and saving it to the specific folder.
Option Explicit
'requires references: "Microsoft HTML Object Library" & "Microsoft Internet Controls"
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, _
ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Declare Function ShowWindow Lib "user32" _
(ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Sub getSS()
Const url = "stackoverflow.com" 'page to get screenshot of (http is added below)
Const fName = "D:\thumb_" & url & ".png" 'output filename (can be png/jpg/bmp/gif)
Const imgScale = 0.25 'scale to 25% (to create thumbnail)
Dim ie As InternetExplorer, ws As Worksheet, sz As Long
Dim img As Picture, oCht As ChartObject
Set ws = ThisWorkbook.Sheets("Sheet1")
Set ie = GetIE()
With ie
.navigate "http://" & url
Do: DoEvents: Loop While .busy Or .readyState <> 4 'wait for page load
ShowWindow Application.hwnd, 5 'activate IE window
Call keybd_event(44, 0, 0, 0) '44="VK_SNAPSHOT"
Pause (0.25) 'pause so clipboard catches up
With ws
ShowWindow Application.hwnd, 5 'back to Excel
.Activate
.Paste
Set img = Selection
With img
Set oCht = ws.ChartObjects.Add(.Left, .Top, .Left + .Width, .Top + .Height)
oCht.Width = .Width * imgScale 'scale obj to picture size
oCht.Height = .Height * imgScale
oCht.Activate
ActiveChart.Paste
ActiveChart.Export fName, Mid(fName, InStrRev(fName, ".") + 1)
oCht.Delete
.Delete
End With
.Activate
End With
.FullScreen = False
.Quit
End With
If Dir(fName) = "" Then Stop 'Something went wrong (file not created)
sz = FileLen(fName)
If sz = 0 Then Stop 'Something went wrong! (invalid filename maybe?)
Debug.Print "Created '" & fName & "' from '" & url & "' (" & sz & " bytes)": Beep
End Sub
Sub Pause(sec As Single)
Dim t As Single: t = Timer
Do: DoEvents: Loop Until Timer > t + sec
End Sub
Function GetIE() As Object
'requires references: "Microsoft HTML Object Library" & "Microsoft Internet Controls"
'return an object for the open Internet Explorer window, or create new one
For Each GetIE In CreateObject("Shell.Application").Windows() 'Loop to find
If (Not GetIE Is Nothing) And GetIE.Name = "Internet Explorer" Then Exit For 'Found!
Next GetIE
If GetIE Is Nothing Then Set GetIE=CreateObject("InternetExplorer.Application") 'Create
GetIE.Visible = True 'Make IE visible
GetIE.FullScreen = True
End Function
Reference:
How to take screenshot of webpage using VBA?
Further, you can modify the code as per your own requirement.

Smooth running marquee text in excel

I am creating a marquee text in Excel 2013. As the Microsoft Web Browser Control doesn't work in Excel 2013 and 2016, so I used the following VBA code:
Sub DoMarquee()
Dim sMarquee As String
Dim iWidth As Integer
Dim iPosition As Integer
Dim rCell As Range
Dim iCurPos As Integer
'Set the message to be displayed in this cell
sMarquee = "This is a scrolling Marquee."
'Set the cell width (how many characters you want displayed at once
iWidth = 10
'Which cell are we doing this in?
Set rCell = Sheet1.Range("M2")
'determine where we are now with the message. InStr will return the position
' of the first character where the current cell value is in the marquee message
iCurPos = InStr(1, sMarquee, rCell.Value)
'If we are position 0, then there is no message, so start over
' otherwise, bump the message to the next characterusing mid
If iCurPos = 0 Then
'Start it over
rCell.Value = Mid(sMarquee, 1, iWidth) Else
'bump it
rCell.Value = Mid(sMarquee, iCurPos + 1, iWidth)
End If
'Set excel up to run this thing again in a second or two or whatever
Application.OnTime Now + TimeValue("00:00:01"), "DoMarquee"
End Sub
It is reflecting in excel every second, is there a way to reflect in milliseconds so that it can show some smooth running. And more issue is, it again starts only after scrolling completely. Is there anyway to make it in a scroll continuously with waiting for the entire text to scroll.
For your sub second functionality use an API call.
Option Explicit
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub DoMarquee()
Dim sMarquee As String
Dim iWidth As Long
Dim iPosition As Long
Dim rCell As Range
Dim iCurPos As Long
sMarquee = "This is a scrolling Marquee."
iWidth = 10
Set rCell = Sheet1.Range("M2")
iCurPos = InStr(1, sMarquee, rCell.Value)
If iCurPos = 0 Then
rCell.Value = Mid(sMarquee, 1, iWidth)
Else
rCell.Value = Mid(sMarquee, iCurPos + 1, iWidth)
End If
Sleep 100
Application.Run "DoMarquee"
End Sub
Drop the PtrSafe if on 32 bit machine so becomes:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Edit:
1) A number of users have noted out of stack space messages to frequency of calls.
#Sorceri has correctly pointed out you can re-work as:
Set rCell = Nothing
DoEvents
Sleep 100
Application.OnTime Now, "DoMarquee"
2) I was unaware of the letter by letter part so I will refer you to his/her answer on the pulling of iWidth into global variable.
That in mind, you may wish to amend the following to take account of #Sorceri's iWidth; I have the following version 2 "fudge" for the hyperlink, amended for out-of-stack, and which includes a test for 32 v 64 bit versions to ensure compatibility. More info on compatibility here.
Version 2:
Option Explicit
#If Win64 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Public Sub DoMarquee()
Dim sMarquee As String
Dim iWidth As Long
Dim iPosition As Long
Dim rCell As Range
Dim iCurPos As Long
sMarquee = "This is a scrolling Marquee."
iWidth = 10
Set rCell = Sheet1.Range("M2")
rCell.Parent.Hyperlinks.Add Anchor:=rCell, Address:="https://www.google.co.uk/", TextToDisplay:=rCell.Text
rCell.Font.ThemeColor = xlThemeColorDark1
iCurPos = InStr(1, sMarquee, rCell.Value)
If iCurPos = 0 Then
rCell.Value = Mid(sMarquee, 1, iWidth)
rCell.Hyperlinks(1).TextToDisplay = rCell.Text
FormatCell rCell
Else
rCell.Value = Mid(sMarquee, iCurPos + 1, iWidth)
On Error Resume Next
rCell.Hyperlinks(1).TextToDisplay = rCell.Text
On Error GoTo 0
FormatCell rCell
End If
Set rCell = Nothing
DoEvents
Sleep 100
Application.OnTime Now, "DoMarquee"
End Sub
Public Sub FormatCell(ByVal rng As Range)
With rng.Font
.Name = "Calibri"
.Size = 11
.Underline = xlUnderlineStyleSingle
.Color = 16711680
End With
End Sub
I couldn't get the example to stop the stack out of space as there were to many calls on the stack to the DoMarquee method. Plus I thought a marquee wrote it out character by character. So using Application.OnTime event to create the marquee. I also took out the iWidth and made it a global variable.
Option Explicit
Private iWidth As Long
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub DoMarquee()
Dim sMarquee As String
Dim iPosition As Long
Dim rCell As Range
Dim iCurPos As Long
Dim txtMarquee As String
sMarquee = "This is a scrolling Marquee."
Set rCell = Sheet1.Range("M2")
'check to see if the cell is empty
If rCell.Value = "" Then
'set the current position to 0 and iWidth to 0
iCurPos = 0
iWidth = 0
Else
'not blank so writing has started. Get the position of the cell text
iCurPos = InStr(1, sMarquee, rCell.Value)
End If
If iCurPos = 0 Then
'it is zero so get the first character
rCell.Value = Mid(sMarquee, iCurPos + 1, 1)
Else
If iWidth < 10 Then
'width is less then ten so we have not written out the max characters,
'continue until width is 10
iWidth = iWidth + 1
rCell.Value = Mid(sMarquee, 1, iWidth)
Else
'maxed the amount to show so start scrolling
rCell.Value = Mid(sMarquee, iCurPos + 1, iWidth)
End If
End If
'release range object
Set rCell = Nothing
'Application.OnTime to stop the stack out of space
DoEvents
Sleep 100
Application.OnTime Now, "DoMarquee"
End Sub

VBA to set Zoom level on Sheets

I have a VBA that will set the zoom level based on the screen resolution.
But its working only for ActiveWindow when you open workbook.
How can I add this across all worksheets in Excel?
Declare Function GetSystemMetrics32 Lib "user32" _
Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
Public Sub ScreenRes()
Dim lResWidth As Long
Dim lResHeight As Long
Dim sRes As String
lResWidth = GetSystemMetrics32(0)
lResHeight = GetSystemMetrics32(1)
sRes = lResWidth & "x" & lResHeight
Select Case sRes
Case Is = "800x600"
ActiveWindow.Zoom = 75
Case Is = "1024x768"
ActiveWindow.Zoom = 125
Case Else
ActiveWindow.Zoom = 100
End Select
End Sub
I will call this module on the Workbook
Private Sub Workbook_Open()
ScreenRes
End Sub
Select all of the Worksheet Objects using the Worksheets collection and the Application.ActiveWindow property will point to them all.
With Worksheets
.Select
ActiveWindow.Zoom = 75
End With
building on #Jeeped answer you could place in ThisWorkbook code pane the following code:
Declare Function GetSystemMetrics32 Lib "user32" _
Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
Option Explicit
Private Sub Workbook_Open()
With Worksheets
.Select
ActiveWindow.zoom = ScreenResToZoom
End With
End Sub
Public Function ScreenResToZoom() As Long
Select Case GetSystemMetrics32(0) & "x" & GetSystemMetrics32(1)
Case Is = "800x600"
ScreenResToZoom = 75
Case Is = "1024x768"
ScreenResToZoom = 125
Case Else
ScreenResToZoom = 100
End Select
End Function

Filling a web form using VBA

So I have been given the task to create new users in the company I work for website. I was given an excel sheet of 100 + usernames and email addresses. I did not want to have to manually do it so is decided to try and write a program. I have never touched VB before, and this is how far I have been able to reach. It works for the first run through the while loop but then I receive an error:
Run-time error '91'
Object variable or With block variable not set
When I try to debug this error, This line in my code becomes highlighted:
IE.document.GetElementsbyname("user_login")(0).Value = ThisWorkbook.Sheets("sheet1").Cells(j, i) ' sets login info
In my Excel Spreadsheet, the email addresses are same as the login info, and they are links to send an email via outlook. I will see if this is causing my error, but in the meantime, I wanted to get a second pair of eyes on this. Thank you for reading this. this is my first post on here so I apologize if it isn't as informative as you'd like
Here is the rest of my code so far
Sub FillInternetForm()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
'create new instance of IE
Dim i As Integer
Dim j As Integer
Dim x As Integer
Dim y As Integer
Dim s As String
s = "paswd" ' pasword setting
i = 4 ' column D for email input
j = 50 ' row to start
x = 9 ' column I For last name input
y = 10 'column j for last name
'you want to use open IE window. Easiest way I know of is via title bar.
While j < 121
Wait
IE.Navigate "website link"
'go to web page listed inside quotes
IE.Visible = True
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
IE.document.GetElementsbyname("user_login")(0).Value = ThisWorkbook.Sheets("sheet1").Cells(j, i) ' sets login info
IE.document.GetElementsbyname("email")(0).Value = ThisWorkbook.Sheets("sheet1").Cells(j, i) ' sets email address
IE.document.GetElementsbyname("first_name")(0).Value = ThisWorkbook.Sheets("sheet1").Cells(j, y) ' sets first name
IE.document.GetElementsbyname("last_name")(0).Value = ThisWorkbook.Sheets("sheet1").Cells(j, x) ' sets last name
Set elementcol = IE.document.getElementsByClassName("button button-secondary wp-generate-pw hide-if-no-js")
elementcol.Item(0).Click 'shows the password
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
IE.document.GetElementsbyname("pass1-text")(0).Value = s 'sets the password
Wait
Set elementcol = IE.document.getElementsByClassName("pw-checkbox")
elementcol.Item(0).Click ' clicks confirmation of weak password choice
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
Set elementcol = IE.document.GetElementsbyname("send_user_notification")
elementcol.Item(0).Click ' unclicks send new user email
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
IE.document.getElementByID("createusersub").Click ' clicks add new user
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
j = j + 1
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
Wend
End Sub
Sub Wait()
Application.Wait Time + TimeSerial(0, 0, 5)
End Sub
EDIT: THIS ERROR ONLY appears after 5 runs through my loop
The cache is probably clogged up from all the looping.
Option Explicit
Private Declare Function FindFirstUrlCacheGroup Lib "wininet.dll" ( _
ByVal dwFlags As Long, _
ByVal dwFilter As Long, _
ByRef lpSearchCondition As Long, _
ByVal dwSearchCondition As Long, _
ByRef lpGroupId As Date, _
ByRef lpReserved As Long) As Long
Private Declare Function FindNextUrlCacheGroup Lib "wininet.dll" ( _
ByVal hFind As Long, _
ByRef lpGroupId As Date, _
ByRef lpReserved As Long) As Long
Private Declare Function DeleteUrlCacheGroup Lib "wininet.dll" ( _
ByVal sGroupID As Date, _
ByVal dwFlags As Long, _
ByRef lpReserved As Long) As Long
Private Declare Function FindFirstUrlCacheEntry Lib "wininet.dll" Alias "FindFirstUrlCacheEntryA" ( _
ByVal lpszUrlSearchPattern As String, _
ByRef lpFirstCacheEntryInfo As INTERNET_CACHE_ENTRY_INFO, _
ByRef lpdwFirstCacheEntryInfoBufferSize As Long) As Long
Private Type INTERNET_CACHE_ENTRY_INFO
dwStructSize As Long
szRestOfData(1024) As Long
End Type
Private Declare Function DeleteUrlCacheEntry Lib "wininet.dll" Alias "DeleteUrlCacheEntryA" ( _
ByVal lpszUrlName As Long) As Long
Private Declare Function FindNextUrlCacheEntry Lib "wininet.dll" Alias "FindNextUrlCacheEntryA" ( _
ByVal hEnumHandle As Long, _
ByRef lpNextCacheEntryInfo As INTERNET_CACHE_ENTRY_INFO, _
ByRef lpdwNextCacheEntryInfoBufferSize As Long) As Long
Private Const CACHGROUP_SEARCH_ALL = &H0
Private Const ERROR_NO_MORE_FILES = 18
Private Const ERROR_NO_MORE_ITEMS = 259
Private Const CACHEGROUP_FLAG_FLUSHURL_ONDELETE = &H2
Private Const BUFFERSIZE = 2048
Private Sub Command1_Click()
Dim sGroupID As Date
Dim hGroup As Long
Dim hFile As Long
Dim sEntryInfo As INTERNET_CACHE_ENTRY_INFO
Dim iSize As Long
On Error Resume Next
' Delete the groups
hGroup = FindFirstUrlCacheGroup(0, 0, 0, 0, sGroupID, 0)
' To avoid error using it with IE4 as FindFirstUrlCacheGroup is not implemented
If Err.Number <> 453 Then
If (hGroup = 0) And (Err.LastDllError <> 2) Then
MsgBox "An error occurred enumerating the cache groups" & Err.LastDllError
Exit Sub
End If
Else
Err.Clear
End If
If (hGroup <> 0) Then
'we succeeded in finding the first cache group.. enumerate and
'delete
Do
If (0 = DeleteUrlCacheGroup(sGroupID, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0)) Then
' To avoid error using it with IE4 as FindFirstUrlCacheGroup is not implemented
If Err.Number <> 453 Then
MsgBox "Error deleting cache group " & Err.LastDllError
Exit Sub
Else
Err.Clear
End If
End If
iSize = BUFFERSIZE
If (0 = FindNextUrlCacheGroup(hGroup, sGroupID, iSize)) And (Err.LastDllError <> 2) Then
MsgBox "Error finding next url cache group! - " & Err.LastDllError
End If
Loop Until Err.LastDllError = 2
End If
' Delete the files
sEntryInfo.dwStructSize = 80
iSize = BUFFERSIZE
hFile = FindFirstUrlCacheEntry(0, sEntryInfo, iSize)
If (hFile = 0) Then
If (Err.LastDllError = ERROR_NO_MORE_ITEMS) Then
GoTo done
End If
MsgBox "ERROR: FindFirstUrlCacheEntry - " & Err.LastDllError
Exit Sub
End If
Do
If (0 = DeleteUrlCacheEntry(sEntryInfo.szRestOfData(0))) _
And (Err.LastDllError <> 2) Then
Err.Clear
End If
iSize = BUFFERSIZE
If (0 = FindNextUrlCacheEntry(hFile, sEntryInfo, iSize)) And (Err.LastDllError <> ERROR_NO_MORE_ITEMS) Then
MsgBox "Error: Unable to find the next cache entry - " & Err.LastDllError
Exit Sub
End If
Loop Until Err.LastDllError = ERROR_NO_MORE_ITEMS
done:
MsgBox "cache cleared"
Command1.Enabled = True
End Sub
http://www.vbforums.com/showthread.php?440508-Clear-IE-Browser-Cache-and-History-with-VBA

VBA Code to Read the Active Program

My hope is to have this macro continually record the name of whatever program is the current active program. I have a user form that runs a timer user a Macro that recalls itself every second. I would like it to record the name of the active window in that same macro and (if different from the last name) append that on to a descriptive string.
I had originally used the "Active window.caption" only to learn that it doesn't apply to other programs (such as chrome, word, or Outlook), But below is a chunk of my code.
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
Whole Macro:
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
To get the Name of the active application/window, you'll need to use API calls.
This Question on the office site should help you.
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
Running the AAA sub should print the title of the active window to the debug console.