简体   繁体   English

从文本文件导入到Excel

[英]Import from text files to Excel

I am trying to write a VBA macro that will prompt the user to choose a directory immediately after running it. 我正在尝试编写一个VBA宏,该宏将提示用户在运行目录后立即选择目录。

Once the user chooses a directory, the macro will scan through all the *.txt files in it and put each of its contents in new row under column G . 用户选择目录后,宏将扫描其中的所有*.txt文件,并将其所有内容放在G列下的新行中。 So, the contents of 1st text file will be in G2 , second text file in G3 and so on. 因此,第一个文本文件的内容将在G2 ,第二个文本文件在G3 ,依此类推。

I browsed StackOverFlow for long and found a working code 我浏览了StackOverFlow很长时间,发现了一个有效的代码

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

I also did some very poor hard-coding to import just one text file into cell G2 我还做了一些非常差劲的硬编码,仅将一个文本文件导入到单元格G2

With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;D:\K\record001_001.txt" _
        , Destination:=Range("$G$2"))
        .Name = "record001_001"
        .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 = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

I do not know how to put these pieces together to have a working code that will. 我不知道如何将这些部分放在一起以形成可以正常工作的代码。

  1. Read all the txt files inside the directory I choose. 阅读我选择的目录内的所有txt文件。
  2. Put each of the text files content in a new row of the same worksheet ( G2 , G3 , etc.) 将每个文本文件内容放在同一工作表的新行中( G2G3等)

Each of those text files have just one or two rows of data and do not want anything to be delimited there. 这些文本文件中的每一个仅具有一两行数据,并且不希望在此处分隔任何内容。 Just copy the whole lot of text in the txt file and paste it in G2 , in a loop until all txt files in the selected directory are done. 只需将整个文本复制到txt文件中,然后循环粘贴到G2 ,直到完成所选目录中的所有txt文件即可。

  1. To Read all the txt files inside the directory or to choose one file 读取目录中的所有txt文件或选择一个文件

The following code should let you choose one or multiple files you want to Import 以下代码应让您选择一个或多个要导入的文件

Application.FileDialog Property (Excel) Application.FileDialog属性(Excel)

    '// Open Dailog
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True <-- Allow multiple selection
        .Show '<-- display the files
    End With
  1. To set Row Number for Data to Begin at G2 then next 设置数据的行号从G2开始,然后下一步

If need update the following code 如果需要更新以下代码

nRow = Range("G2").End(xlUp).Offset(1, 0).row    
Destination:=Range("$G$" & nRow))  


See complete CODE with comments 查看完整的CODE(带注释)

Sub Import()
    '// Declare a variable as
    Dim nRow            As Long
    Dim sExtension      As String
    Dim oFolder         As FileDialog '// FileDialog object
    Dim vSelectedItem   As Variant

    '// Stop Screen Flickering
    Application.ScreenUpdating = False

    '// Create a FileDialog object as a File Picker dialog box
    Set oFolder = Application.FileDialog(msoFileDialogOpen)

    '// Use a With...End With block to reference FileDialog.
    With oFolder
        '// Allow multiple selection.
        .AllowMultiSelect = True
        '// Use the Show method to display the files.
        If .Show = -1 Then

    '// Extension
    sExtension = Dir("*.txt")

    '// Step through each SelectedItems
    For Each vSelectedItem In .SelectedItems

        '// Sets Row Number for Data to Begin
        nRow = Range("G2").End(xlUp).Offset(1, 0).row

        '// Below is importing a text file
        With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;" & sExtension, Destination:=Range("$G$" & nRow))
            .Name = sExtension
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 850
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = True
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = True
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = True
            .TextFileOtherDelimiter = "="
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
        sExtension = Dir
    Next
            '// If Cancel...
            Else
            End If
    End With

    Application.ScreenUpdating = True

    '// Set object to Nothing. Object? see Link Object
    Set oFolder = Nothing
End Sub

Set Object = Nothing 设置对象=空

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM