Forum Discussion
JDGriz
Jun 03, 2023Copper Contributor
VBA Macro
I'm trying to record a simple macro with keystrokes of: "HOME", CTRL+C, CTRL+G, CTRL+V, ENTER So far I have not been successful in recording this simple macro. Any help for this?
SnowMan55
Jun 04, 2023Bronze Contributor
What is usually important is not emulating those keystrokes, but accomplishing the actions represented by them. It seems you are trying to go a destination address that is stored at the start of the currently-selected row.
Consider this code instead:
Sub GoIndirectly1()
Dim in4CurrentRow As Long
Dim strDestination As String
Dim in4PosnOfExcMrk As Long
'
Dim strSheetName As String
Dim strCellAddress As String
'---- Determine the destination from the current selection.
in4CurrentRow = Selection.Row
strDestination = Range("A" & in4CurrentRow).Value
' OTOH, if your use of the HOME key is intended to take the
' user to a different column (e.g., because some early
' columns are hidden, or because Freeze Panes has been used)
' ...if you can't determine the column programmatically,
' you may need to try the SendKeys method of the Application
' object. Avoid that if possible.
' -- Perform a trivial validation on the value obtained.
If Len(strDestination) < 2 Then
Call MsgBox("Invalid destination was found in row " _
& Format$(in4CurrentRow, "#,###,##0") _
, vbExclamation Or vbOKOnly, "GoIndirectly1")
Exit Sub
End If
' If you really need the destination in the copy/paste buffer,
' you can try including a Range.Copy method. But I'll assume
' that is a side effect that you do not require.
'---- Determine what the destination really consists of.
' [Depending on how you specified it...
in4PosnOfExcMrk = InStr(1, strDestination, "!")
If in4PosnOfExcMrk > 0 Then
'...it's an address in another worksheet. The "Go To" dialog
' requires those cell address to be in A1 (not R1C1) format.
' But the Application.GoTo method (below) is more flexible.
strSheetName = Left$(strDestination, in4PosnOfExcMrk - 1)
strCellAddress = Mid$(strDestination, in4PosnOfExcMrk + 1)
' Because the worksheet name might be wrapped in
' apostrophes, and might include doubled apostrophes:
If Right$(strSheetName, 1) = "'" _
And Left$(strSheetName, 1) = "'" _
Then
strSheetName = Mid$(strSheetName, 2, Len(strSheetName) - 2)
strSheetName = Replace(strSheetName, "''", "'")
End If
Else
strCellAddress = strDestination
End If
'---- Go there.
If UCase$(Left$(strCellAddress, 1)) = "R" _
And IsNumeric(Mid$(strCellAddress, 2, 1)) _
And InStr(3, strCellAddress, "C", vbTextCompare) > 0 _
Then
'...the cell address is in R1C1 notation.
Application.Goto strDestination
Else
'...the cell address is in A1 notation.
If Len(strSheetName) > 0 Then
Application.Goto Worksheets(strSheetName).Range(strCellAddress)
Else
Application.Goto Range(strCellAddress)
End If
End If
End Sub
If you really need keystrokes, which I have not always found reliable, then see, e.g., this article: How to Use Excel SendKeys Method in Macros