使用宏导入多个Txt文件

时间:2018-11-28 17:19:00

标签: excel vba excel-vba excel-2016 data-import

我以前在这篇文章中问过这个问题: Importing multiple text files using VBA Macro

过一会儿,我创建了一个全新的工作簿,并且当我尝试将此代码复制/粘贴到宏模块时,我收到了编译错误:未定义用户定义的类型。...代码如下:

Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
Dim sFolder As String, vDB, Ws As Worksheet
Dim rngT As Range
' Get a FileSystem object
  Set fso = New FileSystemObject

' get the directory you want

sFolder = "C:\Users\danial.smith\Documents\Maintenance\DataDump\Reports\RawData\"
Set folder = fso.GetFolder(sFolder)
' set the starting point to write the data to
Set Ws = ActiveSheet
'Set cl = ActiveSheet.Cells(1, 1)

' Loop thru all files in the folder
For Each file In folder.Files
    Workbooks.Open Filename:=sFolder & file.Name, Format:=1
    With ActiveWorkbook.ActiveSheet
        vDB = .UsedRange.Offset(1)
    End With
    ActiveWorkbook.Close
    Set rngT = Ws.Range("a" & Rows.Count).End(xlUp)(2)
    rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub

我已经尝试像某些建议那样包含Microsoft ActiveX数据对象库,但还是没有运气。...不确定该怎么做...

1 个答案:

答案 0 :(得分:2)

FileSystemObject需要对 Microsoft脚本运行时库的引用。

查看上一个工作簿中的参考。