2016-08-09 47 views
2

我正在將幾個CSV文件的內容複製到一個新的CSV文件中,並且無法使用我的vba代碼。我知道CMD工具來複制.csv文件,但這對我不起作用,因爲我的目錄存儲在網絡上,而且我無法從CMD窗口路徑到它(我得到關於使用UNC的錯誤地址)。我的老闆寧願讓代碼無人交互,所以將文件移動到計算機上的目錄,運行CMD,然後將結果移回來不是一種選擇。將許多csv文件編譯爲一個新的csv表

按我的老闆的要求,代碼需要做到以下幾點:

「每個宏運行時,新的主文件應保存在時,它的運行,所以報告中拉各時間相同的文件。 「

這樣做的一個合乎邏輯的結果是,宏應該在生成的文件名中捕獲特定的字符串,並在創建新版本時「跳過」該文件。另外,每個.csv文件都有標題,所以我的範圍設置爲避免複製它們。

以下是我迄今爲止編寫的代碼。當我嘗試運行宏,我可以拿出線的幾個誤區:

Set WorkBk = Workbooks.Open(FolderPath & FileName)

他們總是1004的消息,,他們要麼說我創建文件是隻讀/加密,或者他們告訴我對象「工作簿」的方法'打開'失敗

我需要改變或做些什麼才能讓下面的代碼工作?我對這段代碼很有信心,因爲我稍微從昨天寫的代碼中稍微修改了它,用.xlsx文件做類似的任務。任何幫助非常感謝,謝謝。

Sub CSV_Aggregate() 
' 
' 

' 
' 

Dim CSVAggregation As Worksheet 
Dim SummarySheet As Worksheet 
Dim FolderPath As String 
Dim NRow As Long 
Dim FileName As String 
Dim WorkBk As Workbook 
Dim SourceRange As Range 
Dim DestRange As Range 


' Points the macro to the proper data source (UPDATE THIS LINE TO YOUR DATA SOURCE!!!) 

FolderPath = "\\usilsvr01\[email protected]\Analytical Services\DIA\Offers Data Question to Exclude" 

' Creates a blank workbook to host the aggregation, and names the first worksheet appropriately. 

Set CSVAggregation = Workbooks.Add(xlWBATWorksheet).Worksheets(1) 
Sheets(1).Name = "DIA Aggregation" 

' Heads the worksheet with the relevant fields to be aggregated. 

CSVAggregation.Range("A1:C1") = Array("Manufacturer Number", "Offer Code", "Data Question") 

' Incrementer to keep track of where new rows should be appended. 

NRow = 2 
Dim LastRow As Long 

    ' Call Dir the first time, pointing it to all Excel files in the folder path. 
    FileName = Dir(FolderPath & "*.csv") 


    ' Loop until all .csv files in the source folder have been read. 

    Do While FileName <> "" 

     ' Macro should skip over the previous version of the aggregate file 

     If InStr(1, FileName, "Aggregate") > 0 Then 
      FileName = Dir() 
      End If 

     ' Open a workbook in the folder. 

     Set WorkBk = Workbooks.Open(FolderPath & FileName) 


      ' Loop through data sheets to collect data. 


       Sheets(1).Activate ' Make the sheet active, find where the data is, and select the data. 
        LastRow = WorkBk.Worksheets(1).Cells.Find(What:="*", _ 
        After:=WorkBk.Worksheets(1).Cells.Range("A1"), _ 
        SearchDirection:=xlPrevious, _ 
        LookIn:=xlFormulas, _ 
        SearchOrder:=xlByRows).Row 
       Set SourceRange = WorkBk.Worksheets(1).Range("A2:C" & LastRow) 


       ' Set the destination range to start at column A and 
       ' be the same size as the source range. 

       Set DestRange = DIAAggregation.Range("A" & NRow) 
       Set DestRange = DestRange.Resize(SourceRange.Rows.Count, SourceRange.Columns.Count) 

       ' Copy over the values from the source to the destination. 

       DestRange.Value = SourceRange.Value 

       ' Increment NRow so that data is not overwritten. 

       NRow = NRow + DestRange.Rows.Count 


     ' Close the source workbook without saving changes. 

     WorkBk.Close savechanges:=False 

     ' Use Dir to get the next file name. 

     FileName = Dir() 
    Loop 


    ' Call AutoFit on the destination sheet so that all data is readable. 

    CSVAggregation.Columns.AutoFit 
    CSVAggregation.Rows.AutoFit 

    ' Places cursor on the first sell so document doesn't open highlighted or anywhere besides the top. 

    CSVAggregation.Range("A1").Select 

    ' Creates variable to hold SaveAs name for Aggregation Report. 

    Dim workbook_Name As String 

     workbook_Name = "CSV Aggregate" 


     ' Saves the workbook in the folder that the data is found in (BE SURE TO CHECK TAHT YOU HAVE THE FOLDER/FILES WITH WHICH YOU SHOULD BE WORKING!!!!) 

     ActiveWorkbook.SaveAs FileName:=(FolderPath & workbook_Name), FileFormat:=6 


End Sub 
+1

使用[Workbooks.OpenText方法](https://msdn.microsoft.com/en-us/library/office/ff837097.aspx)打開CSV文件。 – Jeeped

+0

我添加了文本,現在調試器告訴我它期望一個函數或變量,並且我除去/改變了其他任何東西。 –

+1

如果使用cmd命令合併csv的問題是UNC地址,那麼可以使用'pushd' cmd命令將網絡地址映射到本地驅動器,並在使用'popd'完成後釋放映射驅動器。 – hstay

回答

1

好的,我能夠做一些改變,讓我的代碼工作。

下面是最終代碼:

Sub CSV_Aggregate() 
' 
' 

' 
' 

Dim CSVAggregation As Worksheet 
Dim SummarySheet As Worksheet 
Dim FolderPath As String 
Dim NRow As Long 
Dim FileName As String 
Dim WorkBk As Workbook 
Dim SourceRange As Range 
Dim DestRange As Range 


' Points the macro to the proper data source (UPDATE THIS LINE TO YOUR DATA SOURCE!!!) 

FolderPath = "\\usilsvr01\[email protected]\Analytical Services\DIA\Offers Data Question to Exclude\" 

' Creates a blank workbook to host the aggregation, and names the first worksheet appropriately. 

Set CSVAggregation = Workbooks.Add(xlWBATWorksheet).Worksheets(1) 
Sheets(1).Name = "DIA Aggregation" 

' Heads the worksheet with the relevant fields to be aggregated. 

CSVAggregation.Range("A1:C1") = Array("Manufacturer Number", "Offer Code", "Data Question") 

' Incrementer to keep track of where new rows should be appended. 

NRow = 2 
Dim LastRow As Long 

    ' Call Dir the first time, pointing it to all Excel files in the folder path. 
    FileName = Dir(FolderPath & "*.csv") 


    ' Loop until all .csv files in the source folder have been read. 

    Do While FileName <> "" 

     ' Macro should skip over the previous version of the aggregate file 

     If InStr(1, FileName, "Aggregate") > 0 Then 
      FileName = Dir() 
      End If 

     ' Open a workbook in the folder. 

     Set WorkBk = Workbooks.Open(FolderPath & FileName, , True) 


      ' Loop through data sheets to collect data. 


       Sheets(1).Activate ' Make the sheet active, find where the data is, and select the data. 
        LastRow = WorkBk.Worksheets(1).Cells.Find(What:="*", _ 
        After:=WorkBk.Worksheets(1).Cells.Range("A1"), _ 
        SearchDirection:=xlPrevious, _ 
        LookIn:=xlFormulas, _ 
        SearchOrder:=xlByRows).Row 
       Set SourceRange = WorkBk.Worksheets(1).Range("A2:C" & LastRow) 


       ' Set the destination range to start at column A and 
       ' be the same size as the source range. 

       Set DestRange = CSVAggregation.Range("A" & NRow) 
       Set DestRange = DestRange.Resize(SourceRange.Rows.Count, SourceRange.Columns.Count) 

       ' Copy over the values from the source to the destination. 

       DestRange.Value = SourceRange.Value 

       ' Increment NRow so that data is not overwritten. 

       NRow = NRow + DestRange.Rows.Count 


     ' Close the source workbook without saving changes. 

     WorkBk.Close savechanges:=False 

     ' Use Dir to get the next file name. 

     FileName = Dir() 
    Loop 


    ' Call AutoFit on the destination sheet so that all data is readable. 

    CSVAggregation.Columns.AutoFit 
    CSVAggregation.Rows.AutoFit 

    ' Places cursor on the first sell so document doesn't open highlighted or anywhere besides the top. 

    CSVAggregation.Range("A1").Select 

    ' Creates variable to hold SaveAs name for Aggregation Report. 

    Dim workbook_Name As String 

     workbook_Name = "CSV Aggregate" 


     ' Saves the workbook in the folder that the data is found in (BE SURE TO CHECK TAHT YOU HAVE THE FOLDER/FILES WITH WHICH YOU SHOULD BE WORKING!!!!) 

     ActiveWorkbook.SaveAs FileName:=(FolderPath & workbook_Name), FileFormat:=6 


End Sub 

我加了最後的 「\」 的文件路徑聲明。

我也改寫了一套WorkBk路線爲:

設置WorkBk = Workbooks.Open(FOLDERPATH &文件名,真)

這解決了 「只讀」 的錯誤我得到的。

+0

如果以前版本的聚集文件是使用Dir讀取的最後一個文件,則代碼將崩潰,因爲當FileName爲空時,您將嘗試執行「設置WorkBk = Workbooks.Open(FolderPath&FileName,True)」。如果InStr(1,FileName,「Aggregate」)> 0然後'FileName = Dir()'End If'到'If InStr(1,FileName,「Aggregate」)= 0,你可以避免這個潛在的問題然後'並在'WorkBk.Close savechanges:= False'語句之後放置'End If'。 – YowE3K

+0

我已經有了我的代碼! –

+0

好的,如果您已經更改了您的代碼,但它不在我們正在評論的答案中。該答案顯示如果InStr(1,FileName,「Aggregate」)> 0那麼''FileName = Dir()'End If'(如果沒有更多文件,可能會使FileName爲空),然後緊接着通過一個'Set WorkBk = Workbooks.Open(FolderPath&FileName,True)'語句,它將使用空白的FileName和崩潰。 – YowE3K

1

您可以使用pushd命令繞過cmd中的UNC/network文件夾問題。它將一個臨時驅動器號分配給網絡文件夾,並允許您繼續正常操作。

相關問題