首页 > 解决方案 > 需要说明:vba find方法故障排除

问题描述

我正在使用 Find 方法从另一个工作簿中获取单元格值。下面的代码带来了价值。但我想删除激活方法,所以只需使用带有 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

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

标签: vbafind

解决方案


请尝试下一个方法:

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在未激活的工作表中没有意义...

编辑

作为一个例子来澄清你关于在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

推荐阅读