vba excel宏cells.find出于某种原因不会使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14266494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:08:54  来源:igfitidea点击:

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

excelvbaexcel-vbaclipboard

提问by b0x0rz

I have this code as an excel macro.

我将此代码作为excel宏。

  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:

MsgBoxwrites the value correctly, but the What:=MyData.GetTextjust won't work. Why? Or, more importantly, how to fix it?

MsgBox正确写入值,但What:=MyData.GetText只是不起作用。为什么?或者,更重要的是,如何修复它?

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.

如果不清楚,我正在尝试找到与剪贴板中当前值相等的下一个值。我已经引用了 MSForms,所以这不是问题。

If I assign MyData.GetText to a variable and use the variable, the same happens, MsgBoxworks, BUT What:=myvariabledoesn't.

如果我将 MyData.GetText 分配给一个变量并使用该变量,也会发生同样的情况MsgBox,但What:=myvariable不会。

回答by Doug Glancy

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