VBA Macro Tip - Variable content selection

Asked

Viewed 23 times

-1

I’m doing a simple macro, but I’m not getting it. I want the macro to locate the value of a specific cell, that this value is varying while the macro is generating:

Sub teste()
    Range("C1").Select
    Selection.Copy
    Cells.Find(What:="36   ", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
End Sub

Here it is locked always looking for the 36, but I want you to look for the value that is in "C1".

1 answer

1

Create variables during code execution. The variable allows you to refer a value/content to it and repurpose that value/content throughout the macro execution code.

In the example the variable was created conteudoVariavel (can use another name you prefer) and it is used in the "What" parameter of "Find". Adapt and test according to your specific need.

Code with comments, for better understanding.

Sub teste()
    Dim conteudoVariavel As Variant 'declara a variável para a macro
    conteudoVariavel = Range("C1") 'coloca o valor de C1 na variável criada
    
    'agora pode utilizar a variável "conteudoVariavel" em qualque lugar que precisar
    Cells.Find(What:=conteudoVariavel, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
End Sub

Browser other questions tagged

You are not signed in. Login or sign up in order to post.