如何更改每个循环的输出位置并运行多个循环

我在这里有代码循环通过一个文件列表; 打开它们,提取数据并将其移到主工作簿中。 我正在寻找做得到它,所以abel的数据是在列c和d,然后把varo在f和g等我看到的问题是,放置代码是在循环内,所以每个我只是写在上一行,而不是在一个不同的列在一起!

Sub Source_Data() Dim r Dim findValues() As String Dim Wrbk As Workbook Dim This As Workbook Dim sht As Worksheet Dim i Dim tmp Dim counter Dim c As Range Dim firstAddress Dim rng As Range ReDim findValues(1 To 3) findValues(1) = "abel" findValues(2) = "varo" findValues(3) = "Tiger" counter = 0 r = Range("A1").End(xlDown).Row Set rng = Range(Cells(1, 1), Cells(r, 1)) Set This = ThisWorkbook For Each tmp In rng Workbooks.Open tmp Set Wrbk = ActiveWorkbook Set sht = ActiveSheet For i = 1 To 3 With sht.Range(Cells(1, 1), Range("A1").SpecialCells(xlCellTypeLastCell)) Set c = .Find(findValues(i), LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Offset(0, 2).Value Do This.Activate tmp.Offset(0, 2).Value = tmp.Value tmp.Offset(0, 3).Value = firstAddress Set c = .FindNext(c) counter = counter + 1 Loop While Not c Is Nothing And c.Value = firstAddress End If End With Wrbk.Activate Next Wrbk.Close Next tmp End Sub 

**编辑:**我知道这可以通过添加一个乘数的“我”的偏移值,但这使得事情比他们需要是如果我想search50个关键字

这是我的答案,希望能够帮助你,一如既往,如果你需要改进,就告诉我。

 Sub Source_Data() Dim r Dim findValues() As String Dim Wrbk As Workbook Dim This As Workbook Dim sht As Worksheet Dim i Dim tmp Dim counter Dim c As Range Dim firstAddress Dim rng As Range Dim ColNum 'the columns number var ReDim findValues(1 To 3) findValues(1) = "abel" findValues(2) = "varo" findValues(3) = "Tiger" counter = 0 r = Range("A1").End(xlDown).Row Set rng = Range(Cells(1, 1), Cells(r, 1)) Set This = ThisWorkbook For Each tmp In rng Workbooks.Open tmp Set Wrbk = ActiveWorkbook Set sht = ActiveSheet For i = 1 To 3 With sht.Range(Cells(1, 1), Range("A1").SpecialCells(xlCellTypeLastCell)) Set c = .Find(findValues(i), LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Offset(0, 2).Value Do This.Activate Select Case i 'Test var i (the value) Case "abel" 'in case the value (that is a string) is equal to... ColNum = 1 'set the var, with the number of the column you want Case "varo" 'in case the value... ColNum = 2 'Set the column... Case "Tiger" ColNum = 3 Case Else 'In case that the i var not match with anyvalue take this column number ColNum = 20 'the garbage! End Select tmp.Offset(0, ColNum).Value = tmp.Value 'Put the value in the selected columns tmp.Offset(0, ColNum + 1).Value = firstAddress 'and put the value to the next column of the 'selected column Set c = .FindNext(c) counter = counter + 1 Loop While Not c Is Nothing And c.Value = firstAddress End If End With Wrbk.Activate Next Wrbk.Close Next tmp End Sub 

注意:您需要将ColNum var设置为您需要的值,在那里放置真正需要存储i的值的列的数量,下一行是放置i var的地址

你可以改变这两行:

 tmp.Offset(0, 2).Value = tmp.Value tmp.Offset(0, 3).Value = firstAddress 

对此

 tmp.Offset(0, 2 + (i-1)*2).Value = tmp.Value tmp.Offset(0, 3 + (i-1)*2).Value = firstAddress