2016-07-24 127 views
0

自从我上次必须编写任何代码以来,已经有好几年了,但现在我似乎又需要它了。Excel VBA:从搜索另一个表中插入表格中的单元格

为了简化,我已经在A列号7,以及我需要输入另一个号码列B取决于什么号码7涉及在另一个表中的另一个表。

因此,在工作表2中,另一个表的数据范围从1到10列A和B列根据我然后需要它来搜索Sheet2列A中的数字7,并给我列B中的数字,并将其放在第一张表的B列中。

我已经尝试了对于内循环For循环,基于另一个代码,我找到地方,但它已经是很久以前,我需要花时间重新阅读并试图获得接近的解决方案。对于高级编码者来说,这可能是一件容易的事情?不管怎么说,在此先感谢您的帮助!

+0

不需要VBA的:你可以使用查找()公式在Sheet1列B细胞,看起来到Sheet2中列A单元和回报相邻单元格的值 – user3598756

+0

我不知道它会这么容易!非常感谢! – Mike

+0

您是指我的评论还是我的回答? – user3598756

回答

1

不能你曾经帮助没有VBA,那么你可以使用这个

Option Explicit 

Sub main() 
    Dim cell As Range, f As Range 
    Dim rng1 As Range, rng2 As Range 

    Set rng1 = Worksheets("Sht1").Columns(1).SpecialCells(xlCellTypeConstants) '<--Change "Sht1" to your actual sheet1 name 
    Set rng2 = Worksheets("Sht2").Columns(1).SpecialCells(xlCellTypeConstants) '<--Change "Sht2" to your actual sheet2 name 
    For Each cell In rng1 
     Set f = rng2.Find(what:=cell.Value2, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=xlNo) 
     If Not f Is Nothing Then cell.Offset(, 1) = f.Offset(, 1) 
    Next cell 
End Sub 
0

这里是做搜索了两个表的方法有两种。

Sub LoopValues() 
    Application.ScreenUpdating = False 
    Application.Calculation = xlCalculationManual 

    Dim wsSource As Worksheet, wsSearch As Worksheet 
    Dim sourceLastRow As Long, searchLastRow As Long 
    Dim i As Long, j As Long 

    Set wsSource = Worksheets("Sheet3") 
    Set wsSearch = Worksheets("Sheet4") 

    With wsSource 
     sourceLastRow = .Range("A" & Rows.Count).End(xlUp).Row 
     searchLastRow = wsSearch.Range("A" & Rows.Count).End(xlUp).Row 

     For i = 2 To sourceLastRow 

      For j = 2 To sourceLastRow 

       If .Cells(i, 1).Value = wsSearch.Cells(j, 1).Value Then .Cells(i, 2).Value = wsSearch.Cells(j, 2).Value 

      Next 

     Next 

    End With 

    Application.ScreenUpdating = True 
    Application.Calculation = xlCalculationAutomatic 

End Sub 

Sub FindValuesLoop() 
    Application.ScreenUpdating = False 
    Application.Calculation = xlCalculationManual 

    Dim wsSource As Worksheet, wsSearch As Worksheet 
    Dim sourceLastRow As Long 
    Dim i As Long 
    Dim SearchRange As Range, rFound As Range 


    Set wsSource = Worksheets("Sheet3") 
    Set wsSearch = Worksheets("Sheet4") 

    With wsSource 
     sourceLastRow = .Range("A" & Rows.Count).End(xlUp).Row 
     Set SearchRange = wsSearch.Range(wsSearch.Range("A1"), wsSearch.Range("A" & Rows.Count).End(xlUp)) 
     For i = 2 To sourceLastRow 

      Set rFound = SearchRange.Find(What:=.Cells(i, 1).Value, LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) 

      If Not rFound Is Nothing Then .Cells(i, 2).Value = rFound.Offset(0, 1).Value 

     Next 

    End With 

    Application.ScreenUpdating = True 
    Application.Calculation = xlCalculationAutomatic 

End Sub 
相关问题