我正在尝试查找包含文本的单元格。如果我在定义代码的同一工作表中执行搜索,则可以这样做。但是,如果我在另一个工作表中执行搜索,搜索将失败。
注意:我希望这里的问题是我不完全了解如何处理不同工作表/模块/对象之间的遍历。
我的工作簿有两个工作表。第一个称为“ Alpha”:
第二个工作表称为“测试版”:
这是我在Alpha工作表上 定义的代码 。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim Country As String
Dim Element As String
Dim BetaWorksheet As Worksheet
Dim MyRange As Range
' A friendly message to let us know that we've entered BeforeDoubleClick
MsgBox ("You double clicked: " & Selection.Value)
' The following code works as expected.
Country = "Bosnia and Herzegovina"
MsgBox ("That's nice, but let's find Bosnia and Herzegovina" & ".")
FindSomething (Country)
MsgBox ("Notice that " & Country & " is selected in the 'Alpha' worksheet.")
' The next lines of code do not work as expected.
Element = "Californium"
MsgBox ("Now let's look for the element " & Element & " in the 'Beta' worksheet.")
MsgBox ("We start by selecting cell A1 in the 'Beta' worksheet.")
Set BetaWorksheet = ThisWorkbook.Worksheets("Beta")
BetaWorksheet.Activate
Set MyRange = BetaWorksheet.Range("A1")
MyRange.Select
MsgBox ("Now that we've selected A1, let's find " & Element & ".")
FindSomething (Element)
End Sub
Private Sub FindSomething(TheThing As String)
Dim FindResult As Range
MsgBox ("Current worksheet: " & ActiveSheet.Name)
MsgBox ("Searching for: " & TheThing)
Set FindResult = Cells.Find(What:=TheThing, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If (FindResult Is Nothing) Then
MsgBox ("Found nothing")
Else
FindResult.Activate
End If
End Sub
要使用此问题重现示例,请转到Alpha工作簿并双击一个国家。这刚刚开始我的代码。
示例代码的第一部分试图找到(并成功)一个硬编码的国家(即波斯尼亚和黑塞哥维那)。
示例代码的第二部分尝试查找(但失败)硬编码元素(即Californium)。在我看来,问题在于Cells.Find方法仍在Alpha工作表中,而不是Beta工作表中。
任何见解将不胜感激。
顺便说一句...我的问题类似于Finding Cell in another sheet中讨论的问题。在这种情况下,代码在标准模块中定义。我的情况不同是我的代码在特定的工作表上定义。