簡體   English   中英

導入多個CSV到Excel VBA

[英]import multiple csv to excel vba

我想將多個csv文件導入到Excel工作表,但是當第二個csv文件打開時,第一個csv的數據丟失了。

這是我的代碼:

Sub Test_ImportAllFiles()

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    sPath = Application.ThisWorkbook.Path & "\cdr"
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Sub

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles

        vaArray(i) = Application.ThisWorkbook.Path & "\cdr\" & oFile.Name
        row_number = CStr(Cells(Rows.Count, 1).End(xlUp).Row)

        With Sheets("Sheet2").QueryTables.Add("TEXT;" + vaArray(i), Destination:=Sheets("Sheet2").Range("$A$" + row_number))
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = False
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 3
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With

        Dim wb_connection As WorkbookConnection

        For Each wb_connection In ActiveWorkbook.Connections
            If InStr(vaArray(i), wb_connection.Name) > 0 Then
                wb_connection.Delete
                MsgBox "Antonis" & i
            End If
        Next wb_connection
        i = i + 1
    Next
End Sub

計算行數時,是指活動工作表,而這可能不是要將數據寫入其中的工作表。

嘗試類似

Dim x as long
With Sheets("Sheet2")
    row_number = .Cells(.Rows.Count, 1).End(xlUp).Row)
    if row_number > 1 then row_number = row_number + 1
end With
With Sheets("Sheet2").QueryTables.Add("TEXT;" + vaArray(i), _
                                 Destination:=Sheets("Sheet2").Range("$A$" & row_number))

更新 :將一個數字添加到row_number上,否則范圍將重疊,並且由於QueryTable可能不重疊,Excel將移動它們。

是的,您可以為rowcount變量使用數字,只需將字符串連接從+更改為& 僅當雙方都是字符串時,運算符+才可進行串聯,而對於所有數據類型, &運算符都將隱式轉換為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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