Home » excel » excel – VBA find the positional coordinates of the found value

excel – VBA find the positional coordinates of the found value

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have this simple macro that goes to the location where a value is.

Sub dkdk()
    Dim dk As String
    Dim rng
    dk = "Document Type"
    If Trim(dk) <> "" Then
        With Sheets(1).Range("1:10")
            Set rng = .Find(dk, .Cells(.Cells.Count), xlValues, xlWhole, xlByRows, xlNext, _
            False)
            Application.Goto rng, True
            If  Then

            End If
        End With
    End If
End Sub

How can i take in a msgbox the location i.e. Cells(x,y) of the value in the Excel grid?

How to&Answers:

Is this what you want?

Sub dkdk()
    Dim dk As String
    Dim rng As Range

    dk = "Document Type"

    If Trim(dk) <> "" Then
        With Sheets(1).Range("1:10")
            Set rng = .Find(dk, .Cells(.Cells.Count), xlValues, xlWhole, _
                      xlByRows, xlNext, False)

            If Not rng Is Nothing Then
                Application.Goto rng, True
                '<~~ This will give something like $A$1
                MsgBox rng.Address 
                '<~~ This will give something like Cells(1,1)
                MsgBox "Cells(" & rng.Row & "," & rng.Column & ")"
            End If
        End With
    End If
End Sub

Answer:

before the Application.Goto statement, insert the following:

msgbox "rownumber: " & rng.row & ", columnnumber: " & rng.column

and, if you like to error check:

if not rng is nothing then
    msgbox "rownumber: " & rng.row & ", columnnumber: " & rng.column
end if