2017-04-13 98 views
1

我試圖將存儲在一個文件夾中的所有CVS's合併到一個Excel工作表中。合併之後,我將運行一個單獨的宏來處理所有的格式,而不是單獨格式化每個單獨的文件。將CSV合併到1個Excel工作表並刪除標題

下面的代碼是我到目前爲止有:

Sub MergeFiles_Click() 

Dim strSourcePath As String 
Dim strDestPath As String 
Dim strFile As String 
Dim strData As String 
Dim x As Variant 
Dim Cnt As Long 
Dim r As Long 
Dim c As Long 

Application.ScreenUpdating = False 

strSourcePath = Sheet1.Range("G2").Value 

If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\" 

strFile = Dir(strSourcePath & "*.csv") 

Do While Len(strFile) > 0 

    Cnt = Cnt + 1 

    If Cnt = 1 Then 
      r = 6 
     Else 
      r = Cells(Rows.Count, "A").End(xlUp).Row + 1 
    End If 


    Open strSourcePath & strFile For Input As #1 
    Do Until EOF(1) 
      Line Input #1, strData 
      x = Split(strData, ",") 
      For c = 0 To UBound(x) 
       Cells(r, c + 1).Value = Trim(x(c)) 
      Next c 
      r = r + 1 
     Loop 

    Close #1 

    strFile = Dir 
Loop 

Application.ScreenUpdating = True 

If Cnt = 0 Then _ 
    MsgBox "No CSV files were found...", vbExclamation 

End Sub 

這將合併所有CSV文件放到一個表,但每個CSV文件的,佔用了12行頂部的標題和其他無用的信息。

我想保留12行放在Excel中的第一個CSV的頂部,但在將其放入Excel工作表之前,將這12行從其餘文件中刪除。

我基本上只想讓文件看起來像一個文件,而不是看起來像文件被複制並粘貼到表單上。

任何幫助,將不勝感激。

+1

你知道你正在使用的數據,但要意識到CSV格式通常允許將逗號嵌入文字字符串中(用雙引號括起來的字段「就像這樣」)。如果你有這些,你的代碼將會失敗。 –

+0

@RichHolton所以在測試了這個之後,我發現了一些導致問題的例子。我能做些什麼來避免這個問題? –

+1

你可能會發現這個問題/答案有幫助:http://stackoverflow.com/questions/12197274/is-there-a-way-to-import-data-from-csv-to-active-excel-sheet –

回答

3

到現有的代碼最簡單的變化是隻包括代碼,如果Cnt是1只複製第12行,否則忽略它們:

Sub MergeFiles_Click() 

    Dim strSourcePath As String 
    Dim strDestPath As String 
    Dim strFile As String 
    Dim strData As String 
    Dim x As Variant 
    Dim Cnt As Long 
    Dim r As Long 
    Dim c As Long 
    Dim inputRow As Long 

    Application.ScreenUpdating = False 

    strSourcePath = Sheet1.Range("G2").Value 

    If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\" 

    strFile = Dir(strSourcePath & "*.csv") 

    Do While Len(strFile) > 0 

     Cnt = Cnt + 1 

     If Cnt = 1 Then 
      r = 6 
     Else 
      r = Cells(Rows.Count, "A").End(xlUp).Row + 1 
     End If 


     Open strSourcePath & strFile For Input As #1 
     inputRow = 0 
     Do Until EOF(1) 
      Line Input #1, strData 
      'Maintain a count of how many rows have been read 
      inputRow = inputRow + 1 
      'Only process rows if this is the first file, or if we have 
      'already passed the 12th row 
      If Cnt = 1 Or inputRow > 12 Then 
       x = Split(strData, ",") 
       For c = 0 To UBound(x) 
        Cells(r, c + 1).Value = Trim(x(c)) 
       Next c 
       r = r + 1 
      End If 
     Loop 

     Close #1 

     strFile = Dir 
    Loop 

    Application.ScreenUpdating = True 

    If Cnt = 0 Then _ 
     MsgBox "No CSV files were found...", vbExclamation 

End Sub 
+0

感謝這工作完美! –

相關問題