【问题标题】:Import multiple CSV files while adding the file name for each imported file导入多个 CSV 文件,同时为每个导入的文件添加文件名
【发布时间】:2020-04-09 11:29:56
【问题描述】:

我一直在尝试导入多个 CSV 文件,每个文件都有一个唯一的名称。我要做的是:为每个导入的文件添加一个文件名一直填充到结尾的列。

Sub ImportMultipleCSV()

Dim myfiles
Dim i As Integer
Dim j As Integer
Dim Answer

myfiles = Application.GetOpenFilename(filefilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)


    If IsArray(myfiles) Then
    Answer = MsgBox("Delete Files after Import?", vbYesNo + vbQuestion)
        For i = LBound(myfiles) To UBound(myfiles)
            With ActiveSheet.QueryTables.Add(Connection:= _
                "TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End(xlUp).Offset(1, 0))
                .RefreshStyle = xlOverwriteCells
                .AdjustColumnWidth = True
                .TextFileStartRow = 2
                .TextFileParseType = xlDelimited
                .TextFileCommaDelimiter = True
                .Refresh

              'add file name to Seperate column

             Range("A" & Rows.Count).End(xlUp).Offset(0, 7).Value = myfiles(i)
**^^ this line only adds the file name, but I want to fill down.**


            End With

            If Answer = vbYes Then
                Kill myfiles(i)
            End If
        Next i

    Else
        MsgBox "No File Selected"
    End If


Dim xConnect As Object
    For Each xConnect In ActiveWorkbook.Connections
        If xConnect.Name <> "ThisWorkbookDataModel" Then xConnect.Delete
    Next xConnect


'Range("C:C,E:E,G:G").Delete


End Sub

这是我想要实现的输出文件。

感谢任何帮助。非常感谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    改变这个:

    Range("A" & Rows.Count).End(xlUp).Offset(0, 7).Value = myfiles(i)
    

    到这里:

    Range(Range("H" & Rows.Count).End(xlUp).Offset(1), Range("A" & Rows.Count).End(xlUp).Offset(0,7)).Value = myFiles(i)
    

    【讨论】:

    • 哇!那太精彩了!非常感谢。你能解释一下吗?
    • 通过使用 H 列,我从填充前一个文件名之后的下一个可用单元格开始范围。其余的和你写的一致。
    猜你喜欢
    • 2020-08-31
    • 2017-04-13
    • 1970-01-01
    • 2021-09-18
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多