需要说明:vba查找方法排查

Need explanation: vba find method troubleshooting

我正在使用 Find 方法从另一个工作簿中获取单元格值。 下面的代码带来了价值。但我想擦除 Activate 方法,所以只需使用 Block Statements 和 Find 方法来从另一个工作簿中获取值。 'Windows(wb_name).激活

'Sheets("SheetA").Select
'Set rg =Worksheets("SheetA").Range("C:C")
'With rg
'value1 = Cells.Find(What:="11693", After:=ActiveCell, LookIn:=xlFormulas, _
 LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, 
 SearchFormat:=False).Value
'End With

澄清一下,我到底想要什么; in values1 = Cells.Find ...我将 Cells 更改为 rg 但它不起作用。我想知道为什么?我也认为没有必要使用 activate 。我想写一个代码,我将摆脱激活另一个工作簿。所以,只需给源 wb 和 ws 名称和范围来查找值

请尝试下一种方式:

Sub FindInOtherSheet()
  Dim Value1 As String, rg As Range
  Set rg = Workbooks("W1.xlsx").Worksheets("SheetA").Range("C:C")
    With rg
        Value1 = .cells.Find(What:="11693", After:=.cells(1, 1), LookIn:=xlFormulas, _
         LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
         SearchFormat:=False).value
    End With
End Sub

它在范围的第一个单元格之后开始搜索。 ActiveCell 在未激活的情况下没有意义 sheet...

已编辑:

作为一个例子来澄清你的问题 Find 在没有任何匹配的情况下不返回任何错误的“问题”,我会说这应该被认为是一个优势。

您可以通过这种简单的方式简单地检查函数是否返回了一个范围(我将使用上面的代码来举例说明):

Sub FindInOtherSheet()
  Dim Value1 As String, rg As Range, fndCell as Range
  Set rg = Workbooks("W1.xlsx").Worksheets("SheetA").Range("C:C")
    With rg
        set fndCell = .cells.Find(What:="11693", After:=.cells(1, 1), LookIn:=xlFormulas, _
         LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
         SearchFormat:=False)
         'check if Find returned a range:
         If not fndCell is Nothing Then 'if a match has been found
             Value1 = fndCell.value
         Else
             MsgBox "No match has been found...": Exit Sub
         End If
    End With
End Sub