Combining CSV Files into one master file and keep

2019-09-19 03:54发布

I have many CSV. files that I want to combine into one big one, further to that, I also need to keep the File Name in Column 2.

Contents of my CSV file

File Name ABNK102455

Column A
12/215425
12/125485
12/215435

File Name ABNK102456

Column A
12/215425
12/125485
12/215435

Result

Combined.CSV

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

Is this possible, and How?

2条回答
甜甜的少女心
2楼-- · 2019-09-19 04:19
@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

You would need to change the setting of sourcedir to suit your circumstances.

I used a files named q26135599-1.csv and q26135599-2.csv containing your data for my testing. You would need to adjust the setting of mask to suit.

Produces newfile.txt

Best not to try to create newfile.txt as a .csv within your source directory, unless you're really sure that it won't be included in %mask%.

查看更多
姐就是有狂的资本
3楼-- · 2019-09-19 04:21

To get you going ....

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
查看更多
登录 后发表回答