2016-07-24 122 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 
相關問題