Excel VBA:从搜索另一个表中插入表格中的单元格

时间:2016-07-24 09:18:19

标签: mysql excel vba excel-vba

自从我上次编码任何东西以来已经好几年了,但现在我似乎再次需要它。

为了简化,我在A栏中有7号,我需要在B栏中输入另一个号码,具体取决于7与另一张表中另一张表中的号码相关。

因此,在Sheet2中,另一个表在A列中的数字范围为1到10,并且根据B列中的数字。然后我需要它在sheet2的A列中搜索数字7并在B列中给出数字,并且将它放在第一张纸的B列中。

我在For循环中尝试了一个For循环,基于我在某个地方找到的另一个代码,但是很久以前我需要花费数小时重读并试图接近解决方案。对于高级程序员来说,这可能是一件容易的事吗? 无论如何,提前感谢您的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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