0

我想从工作表中取一个名字(比如在名为“Names”的工作表中的 A2)并在另一个工作表中搜索相同的名字(比如“Jobs”中的 A2)。在另一个工作表中找到该名称后,我想从它旁边的单元格中复制值(仍在“工作”但 B2 中)并将其返回到第一个工作表中的不同单元格(E2)(“名称”) . 我最终想遍历“名称”的 A1 中的所有值并填写整张表。

我已经做到了这一点:

Sub fixThis()
    Dim i As Long, j As Long, col1 As Long, col2 As Long, lastrow1 As Long, lastrow2 As Long
    Dim sheetOne As String
    Dim sheetTwo As String

    col1 = 5
    col2 = 1
    sheetOne = "Names"
    sheetTwo = "Job"
    lastrow1 = Cells(Rows.Count, col1).End(xlUp).Row
    lastrow2 = Cells(Rows.Count, col2).End(xlUp).Row

    For i = 2 To lastrow1
        For j = 2 To lastrow2

           If sheetOne.Cells(i, col1).Value = sheetTwo.Cells(j, col2).Value Then

                sheetOne.Cells(i, 6).Value = sheetTwo.Cells(j, 2).Value

           End If
        Next
    Next
End Sub
4

1 回答 1

2

可以将工作表名称存储为字符串。但是当你使用它们时,你需要像这样使用它们来引用工作表对象:Sheets("Sheetname").Cells().Value 或者你可以使用这样的变量:

Dim strSheet1name as String
strSheet1name = "Sheet1"

Sheets(strSheet1name).Cells().Value

最后,如果您真的想要,可以声明自己的工作表对象,例如

Dim ws as worksheets
ws = Sheets("Sheet1")

ws.Cells.value

要保持上述所有代码相同,您需要尝试替换

       If sheetOne.Cells(i, col1).Value = sheetTwo.Cells(j, col2).Value Then

            sheetOne.Cells(i, 6).Value = sheetTwo.Cells(j, 2).Value

       End If

       If Sheets(sheetOne).Cells(i, col1).Value = Sheets(sheetTwo).Cells(j, col2).Value Then

            Sheets(sheetOne).Cells(i, 6).Value = Sheets(sheetTwo).Cells(j, 2).Value

       End If

最后,如果您正在处理多张工作表,则需要在这些行中添加更多细节:

lastrow1 = Cells(Rows.Count, col1).End(xlUp).Row
lastrow2 = Cells(Rows.Count, col2).End(xlUp).Row

并将它们更改为:

lastrow1 = Sheets(SheetOne).Cells(Sheets(SheetOne).Rows.Count, col1).End(xlUp).Row
lastrow2 = Sheets(SheetTwo).Cells(Sheets(SheetTwo).Rows.Count, col2).End(xlUp).Row

最终版本看起来像这样:

Sub fixThis()
    Dim i As Long, j As Long, col1 As Long, col2 As Long, lastrow1 As Long, lastrow2 As Long
    Dim sheetOne As String
    Dim sheetTwo As String

    col1 = 5
    col2 = 1
    sheetOne = "Names"
    sheetTwo = "Job"
    lastrow1 = Sheets(sheetOne).Cells(Sheets(sheetOne).Rows.Count, col1).End(xlUp).Row
    lastrow2 = Sheets(sheetTwo).Cells(Sheets(sheetTwo).Rows.Count, col2).End(xlUp).Row

    For i = 2 To lastrow1
        For j = 2 To lastrow2
            If Sheets(sheetOne).Cells(i, col1).Value = Sheets(sheetTwo).Cells(j, col2).Value Then
                Sheets(sheetOne).Cells(i, 6).Value = Sheets(sheetTwo).Cells(j, 2).Value
            End If
        Next j
    Next i
End Sub
于 2012-07-16T15:02:12.710 回答