簡體   English   中英

在導入到excel的CSV的每個記錄中追加文件名

[英]Append File Name in each record of imported CSV into excel

我編寫了以下宏,該宏從Active Excel電子表格所在的目錄中導入所有CSV文件。 現在,我想在每個記錄的最后一列中添加CSV的相應文件名,但是我不知道該怎么做。 誰能給我指點。

Sub ImportAllCSV()
  Dim FName As Variant, R As Long
  R = 1
  FName = Dir("*.csv")
  Dim counter As Integer, startRow As Integer
  counter = 0
  Do While FName <> ""
    If counter = 0 Then
      startRow = 3
    Else
      startRow = 4
    End If
    load_csv FName, ThisWorkbook.Sheets("Indata").Cells(R, 1), startRow
    R = ThisWorkbook.Sheets("Indata").UsedRange.Rows.Count + 1
    FName = Dir
    counter = counter + 1
  Loop

End Sub

Sub load_csv(fStr As Variant, Position As Range, startRow As Integer)
    With ThisWorkbook.Sheets("Indata").QueryTables.Add(Connection:= _
    "TEXT;" & fStr, Destination:=Position)
        .Name = "CAPTURE"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = startRow
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = True
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False

    End With
End Sub

使用load_csv函數,您僅可以導入csv,但是您可以做更多的事情(例如,在任何地方寫文件名)...還請考慮,在導入時,必須說出必須選擇的文件 這導致一個簡單的想法:文件名應該已經在函數中的某個位置!

提示: fStr

我還建議僅保留導入時所需的命令...這些似乎是用Excel Macro-Recorder記錄的,其中一些可能沒有任何幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM