无需选择或激活即可查找方法

Find method without selecting or activating

我是老乡。 Matlab 很酷,R 也很酷,但现在是 VBA Excel 的时候了。 我想在 "Sheet2"(A 列)中找到一个存储在 "Sheet1"(单元格 A1)中的值。我可以使用 Select 并从一个 sheet 跳到另一个来做到这一点,但我想在没有所有这些跳跃的情况下做到这一点。我想 运行 我的代码,而不是 Excel 在代码 运行ning 时看起来很疯狂。当我 运行 宏时,我希望它 运行 不管我在 Excel 中激活的工作 sheet。 那可能吗?检查我的代码波纹管。 祝大家一切顺利!

Sub FindName()

   Dim Name As String
   Dim TablePosition As Range


   Name = Worksheets("Sheet1").Range("A1").Value

   'If I insert here: Worksheets("Sheet2").Select 
   'The codes runs but just because I am telling him to move to sheet2
   'Why is it not going to Sheet2 with the instruction bellow?

   With Worksheets("Sheet2").Application.Range("A1", Range("A1").End(xlDown))
         Set TablePosition = _
         .Find(What:=Name, _
         After:=Range("A1").End(xlDown), _
         LookIn:=xlValues, _
         LookAt:=xlWhole, _
         Searchorder:=xlByRows, _
         SearchDirection:=xlNext, _
         MatchCase:=False, _
         SearchFormat:=False)

         If Not TablePosition Is Nothing Then
            Application.Goto TablePosition, True
         Else
            MsgBox "Name not specified."
         End If

   End With

End Sub
Worksheets("Sheet2").Application.Range("A1", Range("A1").End(xlDown))

相同
Activesheet.Range("A1", Range("A1").End(xlDown))

因此,除非您在代码运行时位于 Sheet2 上,否则它将搜索错误 sheet。

你应该使用类似的东西:

Dim sht as Worksheet
Set sht = Worksheets("Sheet2")
With sht.Range(sht.Range("a1"), sht.Range("a1").End(xlDown))
'...

我会为您的目标建议一种略有不同的方法。这个函数基本上会在 activesheet 中查找字符串 Name 的第一次出现,前提是您提供了一个列字母(在您的情况下是 A)。如果没有匹配项,它将 return 'N/A' 单元格的地址。

Function FindName(Name As String, columnId As String) As String
Dim LastRow As Long
Dim targetrange As Range
Dim targetsheet As String: targetsheet = ActiveSheet.Name
With ThisWorkbook.Worksheets(targetsheet)
LastRow = .Cells(.Rows.Count, columnId).End(xlUp).Row
Set targetrange = .Range(columnId & "1", columnId & LastRow)
End With
For Each cell In targetrange.Cells
If cell.Value = Name Then
FindName = cell.Address(0, 0)
Exit Function
Else
FindName = "N/A"
End If
Next
End Function

Sub Main()
Debug.Print (FindName("Hi", "A"))
End Sub

输出:

试试这个

Sub test()
    Dim name$, Rng$, Lrow&
    name = Worksheets("Sheet1").[A1].Value
    Lrow = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
    On Error Resume Next
    Rng = Worksheets("Sheet2").Range("A1:A" & Lrow).Find(name).Address
    If Err.Number = 0 Then
        With Worksheets("Sheet2")
            .Activate
            .Range(Rng).Select
        End With
    Else
        Err.Clear: MsgBox "Name not specified."
    End If
End Sub