从一张表中查找文本并将其用于替换另一张表

时间:2017-03-22 00:52:35

标签: excel vba excel-vba

我的Excel文件中有2张(第1页和第2页)。

在工作表1中,有3列 - 代码,ID和文本。这里有100多条记录。

在表2中,有大量数据。

我正在尝试写VBA:

1)找到'代码' (Sheet1)来自Sheet2的第二列;

2)找到ID' (Sheet1)来自Sheet2的第三行并获取列号;

3)粘贴'文字' (Sheet1)位于Sheet2中的相应行和列中。

我已经写下了下面的代码,但它没有粘贴' text'在相应列中 - 而是粘贴在与' ID'

匹配的所有列中

请协助。感谢

Private Sub CommandButton1_Click()

Dim wb As Workbook
Dim sht As Worksheet
Dim rng1 As Range
Dim rngCell_1 As Range
Dim rngCell_2 As Range
Dim rngCell_3 As Range

Set wb = ActiveWorkbook
Set sht2 = ActiveWorkbook.Sheets("Sheet2")
Set sht = wb.Sheets("Sheet1")

With sht2

lastrow = .Cells(Rows.Count, "A").End(xlUp).Row
lastrowcell = sht.Cells(Rows.Count, "A").End(xlUp).Row
For Row = 4 To lastrow
    For Each rngCell_2 In sht.Range("B2:B" & lastrowcell)
    Set rng1 = sht2.UsedRange.Find(rngCell_2, , xlValues, xlWhole)
        For Each rngCell_1 In sht.Range("A2:A" & lastrowcell)
            For Each rngCell_3 In sht.Range("C2:C" & lastrowcell)
                If (.Cells(Row, 2) = rngCell_1) Then
                    .Cells(Row, rng1.Column) = rngCell_3
                    .Cells(Row, rng1.Column).Font.Color = 255
                    End If
            Next rngCell_3
        Next rngCell_1
    Next rngCell_2
Next Row
End With

End Sub

1 个答案:

答案 0 :(得分:0)

我更喜欢Find()来取代嵌套循环:

Private Sub CommandButton1_Click()

    Dim wb As Workbook
    Dim sht1 As Worksheet, sht2 As Worksheet
    Dim rw As Range, f1 As Range, f2 As Range

    Set wb = ActiveWorkbook
    Set sht1 = wb.Sheets("Sheet1")
    Set sht2 = wb.Sheets("Sheet2")

    Set rw = sht1.Range("A2:C2")

    Do While Application.CountA(rw) = 3

        Set f1 = sht2.Columns(2).Find(rw.Cells(1), lookat:=xlWhole)

        If Not f1 Is Nothing Then

            Set f2 = sht2.Rows(2).Find(rw.Cells(2), lookat:=xlWhole)

            If Not f2 Is Nothing Then
                sht2.Cells(f1.Row, f2.Column).Value = rw.Cells(3).Value
            End If

        End If

        Set rw = rw.Offset(1, 0)
    Loop

End Sub
相关问题