【发布时间】:2013-07-19 23:17:29
【问题描述】:
我已经写了这个并且它在大多数情况下都有效......对于我找到的第一个文件。在第二个文件上,我收到以下错误:
“无法粘贴信息,因为复制区域和粘贴区域的大小和形状不同。请尝试以下方法之一:
- 单击单个单元格,然后粘贴。
- 选择一个矩形 大小和形状相同,然后粘贴。”
我不明白我做错了什么。
假设遍历一个目录并抓取那里的所有 .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 交换,它会将所有文件粘贴到工作表中......但它会覆盖它之前的文件。我需要它附加,但不知道如何实现。
【问题讨论】: