我有些挣扎,遍历文件并从每个文件中复制一些信息以进行合并。
因此,我有一个文件列表并有一个打开文件的代码,但就我未遍历i而言,该脚本替换了输入的数据,并且不偏移任何内容。
在遍历多个文件时,能否请您帮我正确的行数?
Sub GetFileCopyData()
Dim SrcWbk As Workbook
Dim DestWbk As Workbook
Dim k As Long
Dim i As Long
Dim wb As Workbook
Set DestWbk = ThisWorkbook
Fname = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a File", MultiSelect:=True)
If VarType(Fname) = vbBoolean Then Exit Sub
'''For i = 1 To UBound(Fname)
For Each file In Fname
MsgBox ("each enetered")
Set SrcWbk = Workbooks.Open(file, UpdateLinks:=False)
i = 1
MsgBox ("set done")
k = SrcWbk.Sheets("Ëèñò2").Cells(2, 1).End(xlDown).Row
SrcWbk.Sheets("Ëèñò2").Range(SrcWbk.Sheets("Ëèñò2").Cells(2, 1), SrcWbk.Sheets("Ëèñò2").Cells(k, 5)).Copy
DestWbk.Sheets("Consolidated").Range(DestWbk.Sheets("Consolidated").Cells(i + 1, 1), DestWbk.Sheets("Consolidated").Cells(k + i - 1, 5)).PasteSpecial
i = i + k
MsgBox ("before close")
SrcWbk.Close True
MsgBox ("before next")
Next file
'''Next i
End Sub
答案 0 :(得分:1)
问题:您将在每次迭代中重新启动i
。因此,将数据粘贴到每个文件的相同位置。
解决方案:将i = 1
移出循环。将其放在For Each file In Fname
代码:
Sub GetFileCopyData()
Dim SrcWbk As Workbook
Dim DestWbk As Workbook
Dim k As Long
Dim i As Long
Dim wb As Workbook
Set DestWbk = ThisWorkbook
fname = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select a File", MultiSelect:=True)
If VarType(fname) = vbBoolean Then Exit Sub
i = 1
'''For i = 1 To UBound(Fname)
For Each file In fname
MsgBox ("each enetered")
Set SrcWbk = Workbooks.Open(file, UpdateLinks:=False)
MsgBox ("set done")
k = SrcWbk.Sheets("Ëèñò2").Cells(2, 1).End(xlDown).row
SrcWbk.Sheets("Ëèñò2").Range(SrcWbk.Sheets("Ëèñò2").Cells(2, 1), SrcWbk.Sheets("Ëèñò2").Cells(k, 5)).Copy
DestWbk.Sheets("Consolidated").Range(DestWbk.Sheets("Consolidated").Cells(i + 1, 1), DestWbk.Sheets("Consolidated").Cells(k + i - 1, 5)).PasteSpecial
i = i + k
MsgBox ("before close")
SrcWbk.Close True
MsgBox ("before next")
Next file
'''Next i
End Sub