我有一个包含许多xls文件的源文件夹。我想创建一个主文件 - 从给定源文件中的所有文件中将所有信息收集到一个数据库中。Excel VBA:在循环中选择一行
下面的代码创建在主文件2列并进入从给定的源文件(一个文件)的2个值:
Sub getData()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim scrFile As String
Dim myPath As String
myPath = ThisWorkbook.path & "\db\" 'The source folder
scrFile = myPath & "1.xlsx" 'Select first file
' Sheet name in the master file is "Sh"
ThisWorkbook.Sheets("Sh").Range("A1").Value = "Column 1"
ThisWorkbook.Sheets("Sh").Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
ThisWorkbook.Sheets("Sh").Range("A2").Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B2").Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
Application.ScreenUpdating = True
End Sub
现在我想通过所有文件循环和从细胞中拯救的值“A10 “和”C5“,因此循环应选择下一行以保存新值。
我有一个想法如何遍历所有文件,但不知道如何切换到下一行:
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
任何帮助将不胜感激! :)
查找最后一行并将其增加1,然后写入下一行。在循环中重复该操作。 [THIS](http://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-vba)将帮助您开始 –