2015-02-09 28 views
0

我的研究員。 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 

回答

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)) 
'... 
+0

高手解答。解決方案的理論解釋! – 2015-02-10 13:33:26

0

我建議稍微不同的方法,以你的目標。該函數基本上會查找activesheet中第一次出現的字符串Name,前提是您提供了一個列字母(在您的情況下這將是A)。如果沒有匹配,它將返回單元格的地址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

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