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

我有很多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 

这是可能的,以及如何?

 @ECHO OFF SETLOCAL SET "sourcedir=U:\sourcedir" SET "mask=q*.csv" SET "headerlinegenerated=" ( FOR /f "delims=" %%a IN ('dir /ad /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的文件, q26135599-2.csv包含您的数据以供testing。 你将需要调整mask的设置来适应。

产生newfile.txt

最好不要尝试在你的源码目录下创build一个.csv文件,除非你确定它不会包含在%mask%

为了让你去…

 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