单击按钮跳转到单元格

时间:2015-07-22 09:35:56

标签: excel excel-vba vba

我有一个excel vb代码,其中我点击了Excel中的一个按钮,转到下一个工作表并根据员工编号搜索该值。我在这段代码中使用了Vlookup。我的问题是光标应该直接转到搜索到的单元格。我的代码如下: -

Private Sub CommandButton3_Click()  
 Sheets("Sheet2").Activate  

Dim rng As Range  
Dim ws1, ws2 As Worksheet  
Dim MyStringVar1 As String  

Set ws1 = ThisWorkbook.Sheets("Sheet1")   
Set ws2 = ThisWorkbook.Sheets("Sheet2")   
Set rng = ws1.Range("c4")   

With ws1     

   MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws2.Range("b3:n13").Value, 5, False)   

    On Error GoTo 0    
   If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1   

End With    


End Sub

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用select代替msgbox

Private Sub CommandButton3_Click()  

Sheets("Sheet2").Activate  

Dim rng As Range  
Dim ws1, ws2 As Worksheet  
Dim MyStringVar1 As String  

Set ws1 = ThisWorkbook.Sheets("Sheet1")   
Set ws2 = ThisWorkbook.Sheets("Sheet2")   
Set rng = ws1.Range("c4")   

With ws1     

   MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws2.Range("b3:n13").Value, 5, False)   

    On Error GoTo 0    
   If MyStringVar1 = "" Then MsgBox "Item not found" Else MyStringVar1.Select

End With    


End Sub

答案 1 :(得分:0)

请尝试查找。

Sub UsingFind()
    Dim ws As Worksheet, sh As Worksheet
    Dim Rws As Long, Rng As Range, c As Range, lookRng As Range

    Set ws = Worksheets("Sheet1")
    Set sh = Worksheets("Sheet2")

    With sh
        Rws = .Cells(Rows.Count, "B").End(xlUp).Row
        Set Rng = .Range(.Cells(1, "B"), .Cells(Rws, "B"))
    End With

    Set lookRng = ws.Range("C4")
    Set c = Rng.Find(what:=lookRng, lookat:=xlWhole)

    If Not c Is Nothing Then
        Application.Goto Reference:=c.OFFSET(0,4)
    Else: MsgBox "Not Found"
        Exit Sub
    End If
End Sub

Find data in another sheet

答案 2 :(得分:0)

我建议你使用for循环严格依赖VB代码 扫描sheet2第1列为等值,一旦发现它将焦点设置在同一行第5列,在下面的示例代码中将只检查10行,您可以根据需要进行调整。

Sub usingvbonly()
Dim key As String
Sheets("sheet1").Select
key = Cells(4, 3).Value 'Value in sheet1 range("C4")
Sheets("sheet2").Select
For i = 1 To 10 Step 1
If Cells(i, 1).Value = key Then
Cells(i, 5).Select
End If
Next i
End Sub