将CSV文件合并为一个主文件,并将文件名保留在第2列中

时间:2014-10-01 06:47:47

标签: excel excel-vba csv cmd vba

我有很多CSV。我想要组合成一个大文件的文件,除此之外,我还需要将文件名保留在第2列。

我的CSV文件的内容

档案名称ABNK102455

Column A
12/215425
12/125485
12/215435

档案名称ABNK102456

Column A
12/215425
12/125485
12/215435

结果

Combined.CSV

Column A
12/215425   ABNK102455
12/125485   ABNK102455
12/215435   ABNK102455
12/215425   ABNK102456
12/125485   ABNK102456
12/215435   ABNK102456

这可能,以及如何?

2 个答案:

答案 0 :(得分:2)

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "mask=q*.csv"
SET "headerlinegenerated="
(
 FOR /f "delims=" %%a IN ('dir /a-d /b "%sourcedir%\%mask%"') DO (
  SET "headerline="
  FOR /f "usebackqdelims=" %%m IN ("%sourcedir%\%%~nxa") DO (
   IF NOT DEFINED headerlinegenerated SET "headerlinegenerated=Y"&ECHO %%m
   IF DEFINED headerline ECHO %%m %%~na
   SET headerline=Y
  )
 )
)>newfile.txt
GOTO :EOF

您需要更改sourcedir的设置以适合您的具体情况。

我使用了一个名为q26135599-1.csvq26135599-2.csv的文件,其中包含我的测试数据。您需要调整mask的设置以适应。

制作newfile.txt

最好不要尝试在源目录中创建newfile.txt作为.csv,除非您确定它不会包含在%mask%中。

答案 1 :(得分:0)

让你去......

Sub Test()
Dim Idx As Long
Dim RowNum As Long
Dim TargetRange As Range
Dim FileName As String

    RowNum = 1
    Set TargetRange = ActiveSheet.[A1]

    ' File selection loop
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = True
        ' use .Filters.Add ... to present only .txt, .csv files etc.
        .Show

        ' File processing loop
        For Idx = 1 To .SelectedItems.Count

            ' here you get each file name inc. full path ... one by one
            FileName = .SelectedItems(Idx)

            ' isolate filename
            ' open file

            ' while not end of file
            '     read from file line by line into a string variable
            '     place string into TargetRange(RowNum, 1)
            '     place filename into TargetRange(RowNum, 2)
            '     increment RowNuM

        Next Idx
    End With
End Sub