簡體   English   中英

將CSV文件與Excel VBA合並

[英]Combine CSV files with Excel VBA

我在一個文件夾中有一些csv文件。 它們都包含3個特定的列。 總列數和順序可能會有所不同。

我想用下划線連接所有3列,並將它們寫在運行代碼的工作表的單列中。

這是我到目前為止的內容:

 Option Explicit

Sub test()

Dim i As Long
Dim LastRow As Long
Dim Columns()

Columns = Array("Column1", "Column2", "Column3")

'Find Columns by Name
For i = 0 To 2
    Columns(i) = Rows(1).Find(What:=Columns(i), LookIn:=xlValues, LookAt:=xlWhole, _
    MatchCase:=False, SearchFormat:=False).Column
Next i

'Debug.Print Columns(0)
'Debug.Print Columns(1)
'Debug.Print Columns(2)

LastRow = Cells(Rows.Count, "A").End(xlUp).Row


For i = 2 To LastRow
    Cells(i, 1) = Cells(i, Columns(0)) & "_" & Cells(i, Columns(1)) & "_" & Cells(i, Columns(2))
Next i

End Sub

如您所見,這滿足了我的要求,但僅適用於活動工作表。 我實際上想循環遍歷與活動工作表相同的文件夾中的所有csv文件,並將結果寫入運行該代碼的工作表的第一工作表,第一列(這顯然不是csv本身)。 我怎樣才能做到這一點?

謝謝!

這是將遍歷文件夾的代碼

Sub Button1_Click()
    Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook

    Set Wb = ThisWorkbook
    'change the address to suite
    MyDir = "C:\WorkBookLoop\"
    MyFile = Dir(MyDir & "*.xls")    'change file extension
    ChDir MyDir
    Application.ScreenUpdating = 0
    Application.DisplayAlerts = 0

    Do While MyFile <> ""
        Workbooks.Open (MyFile)

        'do something here




        MyFile = Dir()
    Loop

End Sub

這取決於您如何命名從CSV文件創建的工作表。 您可以將所有工作表添加到集合中,並使用For...Each循環在該循環中執行整個搜索和連接過程。 請注意,您必須明確定義第一個工作表名稱,因為該名稱不會在連續的循環中更改:

Option Explicit

Sub test()

Dim i As Long
Dim LastRow As Long
Dim Columns()
Dim frontSheet as Worksheet
Dim wSheets as New Collection
Dim ws as Worksheet

Set frontSheet = Sheets("name of front sheet")

'Add all your CSV sheets to wSheets using the .Add() method.
For Each ws in wSheets

    Columns = Array("Column1", "Column2", "Column3")

    'Find Columns by Name
    For i = 0 To 2
        Columns(i) = ws.Rows(1).Find(What:=Columns(i), LookIn:=xlValues, LookAt:=xlWhole, _
        MatchCase:=False, SearchFormat:=False).Column
    Next i

    'Debug.Print Columns(0)
    'Debug.Print Columns(1)
    'Debug.Print Columns(2)

    LastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row


    For i = 2 To LastRow
        frontsheet.Cells(i, 1) = ws.Cells(i, Columns(0)) & "_" & ws.Cells(i, Columns(1)) & "_" & ws.Cells(i, Columns(2))
    Next i

Next ws

End Sub

在excel中打開CSV文件通常很慢而且很費勁,但是VBA可以使用TextStream它們讀取為文本文件。 此外,文件腳本對象使您可以直接使用文件和目錄。 如果您以后不需要將文件保留在工作表中,則類似的方法可能是更好的方法:

Sub SearchFoldersForCSV()

Dim fso As Object
Dim fld As Object
Dim file As Object
Dim ts As Object
Dim strPath As String
Dim lineNumber As Integer
Dim lineArray() As String
Dim cols() As Integer
Dim i As Integer
Dim frontSheet As Worksheet
Dim frontSheetRow As Integer
Dim concatString As String

Set frontSheet = Sheets("name of front sheet")
frontSheetRow = 1

strPath = "C:\where-im-searching\"

Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(strPath)

For Each file In fld.Files

    If (Right(file.Name, 3) = "csv") Then

        Debug.Print file.Name

        Set ts = file.OpenAsTextStream()

        lineNumber = 0

        Do While Not ts.AtEndOfStream

            lineNumber = lineNumber + 1
            lineArray = Split(ts.ReadLine, ",")

            If (lineNumber = 1) Then

                'We are at the first line of the .CSV so
                'find index in lineArray of columns of interest

                'Add extra ElseIf as required

                For i = LBound(lineArray) To UBound(lineArray)
                    If lineArray(i) = "Column 1" Then
                        cols(1) = i
                    ElseIf lineArray(i) = "Column 2" Then
                        cols(2) = i
                    ElseIf lineArray(i) = "Column 3" Then
                        cols(3) = i
                    End If
                Next i

            Else

                'Read and store the column of interest from this
                'row by reading the lineArray indices found above.

                concatString = ""
                For i = LBound(cols) To UBound(cols)
                    concatString = concatString & lineArray(i) & "_"
                Next i

                concatString = Left(concatString, Len(concatString) - 1)

                frontSheet.Cells(frontSheetRow, 1).Value = concatString
                frontSheetRow = frontSheetRow + 1

            End If

        Loop

        ts.Close

    End If

Next file

End Sub

您可以在此處找到有關FileSystemObjectTextStream更多信息。

暫無
暫無

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

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