查找方法而不选择或激活

时间:2015-02-09 20:52:56

标签: excel vba select find

我是研究员。 Matlab很酷,而R也是,但现在是VBA Excel的时候了。 我想找到" Sheet2" (A列)存储在" Sheet1"中的一个值。 (单元格A1)。我可以使用Select和从一张纸跳到另一张,但我想在没有这些跳跃的情况下做到这一点。我希望在代码运行时运行我的代码,而不会让Excel看起来狂热。我希望它在运行宏时不会运行我在Excel中激活的工作表。 那可能吗?检查我的代码。 对你们所有人来说都是最好的!

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

3 个答案:

答案 0 :(得分:0)

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

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

因此,除非您的代码运行时在Sheet2上,否则它将搜索错误的工作表。

你应该使用类似的东西:

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

答案 1 :(得分:0)

我建议你的目标略有不同。此函数基本上会查找Name中第一次出现的字符串activesheet,前提是您提供了一个列字母(在您的情况下为A)。如果没有匹配,它将返回'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

输出:

enter image description here

答案 2 :(得分:0)

试试这个

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