使用for循环和数组比较来自不同工作表的两个单元格

我有一个单元格A1的列表lastrow在工作表“input这里”,我有一个完整的string值的单元格A1到A692我已经存储在数组svr的“string列表”工作表上的列表。 我想要发生的是macros检查工作表“input这里”列A上的所有值,并将其与数组svr内的值逐一比较,直到它find匹配,并且当它这样做时,它将复制一个范围单元格从工作表“string列表”工作表“input这里”。 我已经尝试了下面的代码,我认为它需要更多的工作。

 Sub Main_SvrLst() Dim inp As Worksheet Dim lst As Worksheet Dim svr(691) As String Set inp = ThisWorkbook.Sheets("Input Here") Set lst = ThisWorkbook.Sheets("String List") lr = inp.Cells(Rows.Count, 1).End(xlUp).Row For svrctr = 0 To 691 svr(svrctr) = lst.Range("A2").Offset(svrctr, 0).Value Next svrctr For a = 2 To lr If inp.Cells(a, 1) = svr(a) Then Worksheets("String List").Activate lst.Range(Cells(a, 2), Cells(a, 8)).Copy inp.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial Worksheets("Input Here").Activate End If Next a End Sub 

我已经更改了一些你的名字,以便更清楚的识别。

也closures设置你的Array以获得正确的号码参考

  Sub Main_SvrLst() Dim inp As Worksheet Dim lst As Worksheet Dim svr(691) As String Set inp = ThisWorkbook.Sheets("Input Here") Set lst = ThisWorkbook.Sheets("String List") Dim LastRowOfInputHere As Long LastRowOfInputHere = inp.Cells(Rows.Count, 1).End(xlUp).Row Dim svrctr As Long 'Made it 2 to 691 to off set your Header Row 'This way the Array position and the row number are the same For svrctr = 2 To 691 svr(svrctr) = lst.Cells(svrctr, "A").Value Next svrctr Dim InputHereRowReference As Long Dim StringListArrayReference As Long 'With your original text it was comparing a two row offset between the "Input" and "String" Sheets For InputHereRowReference = 2 To LastRowOfInputHere For StringListArrayReference = 2 To 691 If inp.Cells(InputHereRowReference, 1) = svr(StringListArrayReference) Then lst.Activate lst.Range(Cells(StringListArrayReference, 2), Cells(StringListArrayReference, 8)).Copy inp.Activate inp.Cells(InputHereRowReference, 2).PasteSpecial End If Next StringListArrayReference Next InputHereRowReference End Sub 

而不是使用VBA代码,你可以在你的“input这里”表中使用公式来做到这一点:

B2

 =""&IFERROR(INDEX('String List'!$A:$H, MATCH($A2, 'String List'!$A:$A, 0), COLUMN()), "") 

把这个公式复制到H2 ,直到你的input完成。