将许多csv文件编译为单个新的csv表

时间:2016-08-09 16:54:04

标签: excel vba excel-vba csv

我正在努力将多个CSV文件的内容复制到一个新的CSV文件中,并且我的vba代码出现问题。我知道CMD工具要复制.csv文件,但这对我不起作用,因为我的目录存储在网络上,我无法从CMD窗口找到它(我收到有关使用的错误) UNC地址)。我的老板更喜欢代码没有人为干预,因此将文件移动到计算机上的目录,运行CMD,然后将结果移回来不是一种选择。

根据我老板的要求,代码需要执行以下操作:

"每次运行宏时,新的主文件都应该在运行时保存,以便每次报告都会提取相同的文件。"

这样做的一个合乎逻辑的结果是宏应该在生成的文件名中捕获一个特定的字符串,并且"跳过"制作新版本时的那个文件。此外,每个.csv文件都有标题,因此我的范围设置为避免复制它们。

以下是我到目前为止编写的代码。当我尝试运行宏时,我得到一些错误来提出该行:

Set WorkBk = Workbooks.Open(FolderPath & FileName)

他们总是 1004条消息,他们要么说我创建的文件是只读/加密的,要么告诉我方法'打开&#39 ;对象'工作簿'失败

我需要更改或执行以下代码才能运行?我对这段代码很有信心,因为我从昨天写的代码中略微修改了它,用.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\lin@mktg\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

2 个答案:

答案 0 :(得分: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\lin@mktg\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

我在FilePath声明中添加了最后一个“\”。

我还将设置的WorkBk行改写为:

设置WorkBk = Workbooks.Open(FolderPath&amp; FileName ,, True)

这解决了我遇到的“只读”错误。

答案 1 :(得分:1)

您可以使用pushd命令绕过cmd中的UNC /网络文件夹问题。它会为网络文件夹分配一个临时驱动器号,并允许您继续正常运行。