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
答案 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
输出:
答案 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