单元格的有条件副本从不同的工作表

我想从工作表中取一个名字(比方说名为“名称”的工作表中的A2),然后在另一个工作表(在“工作”中称为A2)中search相同的名称。 在另一个工作表中find这个名字之后,我想从它旁边的单元格中复制值(仍然在'Jobs'中但是B2),并将它返回到第一个表格('Names')中的另一个单元格(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 

如果将表格名称存储为string,那也没问题。 但是当你使用它们时,你需要使用它们来像这样引用表单对象: Sheets("Sheetname").Cells().Value或者你可以使用像这样的variables:

 Dim strSheet1name as String strSheet1name = "Sheet1" Sheets(strSheet1name).Cells().Value 

最后,如果你真的想要你可以声明自己的表单对象

 Dim ws as worksheets ws = Sheets("Sheet1") ws.Cells.value 

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

  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