[英]Import Multiple space delimited files into one Excel Sheet
我已经写了这个,它在大多数情况下都起作用...对于我找到的第一个文件。 在第二个文件上,出现以下错误:
“由于复制区域和粘贴区域的大小和形状不同,因此无法粘贴信息。请尝试以下一种方法:
我不明白我在做什么错。
假设遍历目录并获取其中的所有.txt文件,然后将它们导入Sheet1或Sheet2。 我可以很好地导入第一个文件,但是下一个文件会抛出该错误,而不是附加到同一电子表格中。
Sub PopulateSheets()
Dim file As String, path As String, fullpath As String, StaticPath As String
Dim count As Integer
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Dim Sheet As String
Dim RowCount As Long
On Error GoTo Errorcatch
RowCount = 1
count = 1
StaticPath = Sheet3.Cells(2, 7)
While (count <= 2)
If count = 1 Then
path = StaticPath & "\com\*.txt"
Else
path = StaticPath & "\res\*.txt"
End If
file = Dir(path)
Sheet = "Sheet" & count
While (file <> "")
fullpath = Left(path, InStr(1, path, "*.txt") - 1) & file
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets(Sheet) '<~~ Sheet where I want to import
Set wbO = Workbooks.Open(fullpath)
RowCount = wsI.Range("A:A").CurrentRegion.Rows.count
wbO.Sheets(1).Cells.Copy Destination:=wsI.Range("A" & RowCount)
wbO.Close SaveChanges:=False
file = Dir 'Grab Next File
Wend
count = count + 1
Wend
Exit Sub
Errorcatch:
MsgBox Err.Description
End Sub
在粘贴第一个文件中的信息,将其关闭后,尝试粘贴第二个文件后,它在wbO.Sheets(1).Cells.Copy Destination:=wsI.Range("A" & RowCount)
。
任何帮助将不胜感激。
旁注,我注意到,如果我将wbO.Sheets(1).Cells.Copy Destination:=wsI.Range("A" & RowCount)
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Sheets(1).Cells.Copy Destination:=wsI.Range("A" & RowCount)
与wbO.Sheets(1).Cells.Copy wsI.Cells
,它将粘贴所有文件都放入工作表中...但是它会覆盖文件之前的文件。 我需要附加它,但不确定如何实现。
您无需“重置” path
的值。 如果您的路径是“ C:\\ MyFolder”(例如),则在循环中的第一次,您的path
是
“ C:\\ MyFolder \\ com \\ *。txt”
当您再次经历循环时,路径变为...
“ C:\\ MyFolder \\ com \\ *。txt \\ res \\ *。txt”
...这会创建无效的路径。 按照以下更新代码。
count = count + 1
' ADD THE LINE BELOW TO YOUR CODE
path = Sheet3.Cells(2, 7)
我通过交换While(File <>“”)循环中的逻辑来回答我的问题:
fullpath = Left(path, InStr(1, path, "*.txt") - 1) & file
Set wbO = Workbooks.Open(fullpath)
RowCount = wsI.UsedRange.Rows.count
SourceRowCount = wbO.Sheets(1).Range("A:A").CurrentRegion.Rows.count
If RowCount <> 1 Then
RowCount = RowCount + 2
SourceRowCount = RowCount + SourceRowCount
End If
wbO.Sheets(1).Range("$A$1:$n$" & SourceRowCount).Copy Destination:=wsI.Range("A" & RowCount & ":$n$" & SourceRowCount)
wbO.Close SaveChanges:=False
file = Dir 'Grab Next File`
我让行计数每次加两个,以便在导入之间留一个空白。 现在一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.