2016-08-09 17 views
2

複数のCSVファイルの内容を1つの新しいCSVファイルにコピーしようとしていますが、私のVBAコードに問題があります。私は、.csvファイルをコピーするCMDツールを認識していますが、私のディレクトリはネットワーク上に保存されているため、CMDウィンドウからパスできません(UNC住所)。私の上司は、コードが人間とのやりとりをゼロにすることを好みます。そのため、ファイルをコンピュータ上のディレクトリに移動し、CMDを実行してから結果を戻すことは選択肢にはなりません。私の上司の要求パー多くのcsvファイルを1つの新しいCSVシートにコンパイルします

、コードは次の操作を実行する必要があります。

レポートが同一のファイルを毎回引っ張るので、実行していたときに、「マクロが実行されるたびに、新しいマスターファイルを経由保存する必要があります。 "

論理的には、新しいバージョンを作成するときにマクロが結果ファイル名の特定の文字列をキャッチし、そのファイルをスキップする必要があります。また、すべての.csvファイルに見出しがあるので、コピーしないように範囲が設定されています。

以下はこれまでに書いたコードです。私はマクロを実行しようとすると、私はいくつかのエラーは、ラインを思い付くことを得る:

Set WorkBk = Workbooks.Open(FolderPath & FileName)

彼らは常に1004メッセージ、だと、彼らは私の作成したファイルがあると言うのいずれか読み取り専用のいずれか/暗号化されている、または彼らは教えてくれます。オブジェクト 'Workbooks'の 'Open'メソッドが失敗しました

以下のコードを動作させるには、何を変更する必要がありますか?私は昨日、.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

私はTextを追加しましたが、デバッガは関数や変数を期待していますが、何も削除/変更しませんでした。 –

+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(フォルダパス&ファイル名、トゥルー)

+0

集計ファイルの前のバージョンがDirを使用して最後に読み込まれたファイルの場合、FileNameがブランクのときに 'Set WorkBk = Workbooks.Open(FolderPath&FileName、True)'を実行しようとするため、コードがクラッシュします。 InStr(1、FileName、 "Aggregate")= 0の場合は、If InStr(1、FileName、 "Aggregate")= 0の場合、 'FileName = Dirそして 'WorkBk.Close savechanges:= False'文の後ろに' End If'を置きます。 – YowE3K

+0

私はすでに自分のコードでそれを持っています! –

+0

良いですが、私たちがコメントしている答えにないコードを変更した場合はOKです。その答えは、If InStr(1、FileName、 "Aggregate")> 0 Then If '' FileName = Dir() '' End If'(ファイルがなくなった場合にFileNameを空白のままにする可能性があります) Set WorkBk = Workbooks.Open(FolderPath&FileName、True) 'ステートメントは、空のFileNameとクラッシュを使用します。 – YowE3K

1

コマンドを使用して、cmdというUNC /ネットワークフォルダの問題を回避することができます。一時的なドライブ文字をネットワークフォルダに割り当て、通常どおり続けることができます。

関連する問題