vba - 需要说明: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 名称和范围即可查找值
解决方案
请尝试下一个方法:
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
推荐阅读
- python-3.x - Python |S1 向量到字符串
- python - 使用 2D numpy 数组的每一行创建 1D numpy 数组的元组列表
- java - 如何使用 log4j2.properties 文件将不同级别的日志发送到不同的附加程序?
- python - 循环列表列表,但 if 语句似乎无法正常工作
- javascript - 推入数组并循环,直到数组长度达到3
- r - 根据其他列的条件选择列中的最大值
- angular - 在参数中访问自定义 RxJS 运算符中的流变量
- c# - 使用 Web SDK 构建交互式控制台应用程序
- python - 在 CPython 中,哪个结构用于实现用户定义的类及其实例
- c# - 如何在 MySql 和 C# 中存储存储过程选择查询的返回值