【问题标题】:Excel VBA: Import data from all text files in a directory onto a new row in excel?Excel VBA:将目录中所有文本文件中的数据导入excel中的新行?
【发布时间】:2015-05-26 12:06:36
【问题描述】:

我正在使用 VBA 将单个文本文件中的所有数据导入 excel 中的新行,然后在导入文本文件中的数据后将文本文件移动到另一个位置/目录。我做了这么多。

但是现在我在一个目录中有多个文本文件,并且想从每个文本文件中获取数据并将其插入新行,所以我最终得到以下结果:

Text File 1
A
B
C
D


Text File 2
T
L
V
P


Excel:
Column A     Column B       Column C         Column D        
A            B              C                D   
T            L              V                P

这是我的代码:

Sub ImportFile()

    Dim rowCount As Long

    rowCount = ActiveSheet.UsedRange.Rows.Count + 1

    If Cells(1, 1).Value = "" Then rowCount = 1


    Close #1
    Open "Z:\Incident Logs\Unactioned\IN94LQ3Z.txt" For Input As #1
    A = 1
     Do While Not EOF(1)
            Line Input #1, TextLine
            Cells(rowCount, A) = TextLine
            A = A + 1
        Loop
    Close #1


 Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
srcPath = "Z:\Incident Logs\Unactioned\"
destPath = "Z:\Incident Logs\Actioned\"
ext = Array("*.txt", "*.xls")
For Each x In ext
    d = Dir(srcPath & x)
        Do While d <> ""
            srcFile = srcPath & d
            FileCopy srcFile, destPath & d
            Kill srcFile
            d = Dir
        Loop
Next


End Sub

请有人告诉我一种做我需要的方法吗?提前致谢

【问题讨论】:

    标签: vba excel text-files


    【解决方案1】:

    您需要将以下 sn-p 合并到您的代码中,在其中替换硬编码的文件路径和文件名。此外,您还需要确保在打开新文件时拥有正确的索引。

    Sub AllFilesInFolder()
        Dim myFolder As String, myFile As String
        myFolder = Application.FileDialog(msoFileDialogFolderPicker)
        With Application.FileDialog(msoFileDialogFolderPicker)
            .AllowMultiSelect = False
            .Show
            If .SelectedItems.Count > 0 Then
                myFolder = .SelectedItems(1)
            End If
        End With
        myFile = Dir(myFolder & "\*.txt") '
        Do While myFile <> ""
            Open myFolder & "\" & myFile For Input As #1
            .....
    
            myFile = Dir
        Loop
    End Sub
    

    【讨论】:

    • 很抱歉,我不明白您的回答,您是否可以向我展示您的代码如何与我的代码一起使用?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多