簡體   English   中英

將多個以空格分隔的文件導入一個Excel工作表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM