使用查找方法从另一个工作表中搜索字符串

时间:2018-08-13 14:34:56

标签: vba excel-vba find

也许我只是没有使用正确的搜索词,我还是VBA的新手,但是我找不到解决问题的方法:

我正在尝试从另一工作表的行中的一个工作表中查找一个值(格式为“ yyyy-ww”),然后选择该单元格(下一步将是选择并复制相应的列,然后然后粘贴值)。

我有以下代码:

Private Sub Button5_Click()


'Define previous week and the search range

Dim prevwk As Object
Dim SrchRng As Range

Set prevwk = ActiveWorkbook.Worksheets("Values").Range("B1")
Set SrchRng = ActiveWorkbook.Worksheets("DE").Rows(1)


'If previous week is found, select the cell

With SrchRng

Dim prevwkf As Range
Set prevwkf = SrchRng.Find(What:=prevwk)

prevwkf.Select   '<----- Error is here

End Sub

我一直收到错误消息:

  

“运行时错误'91':对象变量或未设置块变量”。

我尝试了许多更改,但是一直到出现此错误消息。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在选择单元格之前,必须像手动操作一样激活工作表:

SrchRng.parent.Activate
prevwkf.Select 

顺便说一句,您不需要With SrchRng,就可以检查是否找到了实际匹配项

Private Sub Button5_Click()
    'Define previous week and the search range
    Dim prevwk As Object
    Dim SrchRng As Range

    Set prevwk = ActiveWorkbook.Worksheets("Values").Range("B1")
    Set SrchRng = ActiveWorkbook.Worksheets("DE").Rows(1)

    'If previous week is found, select the cell
    Dim prevwkf As Range
    Set prevwkf = SrchRng.Find(What:=prevwk)
    If Not prevwkf Is Nothing Then ' check you actually found something
        SrchRng.Parent.Activate
        prevwkf.Select '<----- Error is here
    End If
End Sub