我想从一张纸上取一个名字(让我们在名为'Names'的表格中说A2)并在另一张工作表中搜索相同的名字(比如'Jobs'中的A2)。在另一个工作表中找到该名称之后,我想从它旁边的单元格中复制值(仍然在'Jobs'但B2中)并将其返回到第一个工作表中的另一个单元格(E2)('Names') 。我最终希望循环“名称”的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
答案 0 :(得分: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