Home » excel » vba – excel macro cells.find won't use variable for some reason

vba – excel macro cells.find won't use variable for some reason

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have this code as an excel macro.

  Dim MyData As DataObject
  Set MyData = New DataObject
  MyData.GetFromClipboard

  MsgBox MyData.GetText

  On Error GoTo NotFound
  Cells.Find(What:=MyData.GetText, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
  :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
  False, SearchFormat:=False).Activate

  NotFound:

MsgBox writes the value correctly, but the What:=MyData.GetText just won’t work. Why? Or, more importantly, how to fix it?

If it is not clear, I am trying to find the next value equal to the one in clipboard at the moment. I have referenced the MSForms so that is not the problem.

If I assign MyData.GetText to a variable and use the variable, the same happens, MsgBox works, BUT What:=myvariable doesn’t.

How to&Answers:

Not sure why this works, but it does:

Sub test()
Dim MyData As DataObject
Dim rng As Excel.Range

Set MyData = New DataObject
MyData.GetFromClipboard
Set rng = ActiveSheet.Cells.Find(What:=MyData.GetText, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
                                 :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
                                 False, SearchFormat:=False)

rng.Activate
End Sub