更改代码以允许选择多个文件

时间:2018-10-26 09:30:08

标签: excel vba file import

我一直在使用宏将多个.txt文件导入到我的有效excel工作簿中(请参见下文)。我希望以允许我选择要导入的文件的方式进行更改,否则将以相同的方式起作用。我尝试使用“ Application.GetOpenFilename(FileFilter:=“文本文件( .txt), .txt”,MultiSelect:= True,标题:=”要打开的文本文件“)”,但出现类型不匹配错误。 我觉得这不应该是大问题,但是我似乎无法解决此问题。

任何建议都非常感谢。

Sub TxtImporter()
Dim f As String, flPath As String
Dim i As Long, j As Long
Dim ws As Worksheet

Application.DisplayAlerts = False
Application.ScreenUpdating = False

flPath = ThisWorkbook.Path & Application.PathSeparator
i = ThisWorkbook.Worksheets.Count
j = Application.Workbooks.Count
f = Dir(flPath & "*.txt")

Do Until f = ""
    Workbooks.OpenText flPath & f, _
        StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True, _
        Space:=False, Other:=False, TrailingMinusNumbers:=True
    Workbooks(j + 1).Worksheets(1).Copy After:=ThisWorkbook.Worksheets(i)
    ThisWorkbook.Worksheets(i + 1).Name = Left(f, Len(f) - 4)
    Workbooks(j + 1).Close SaveChanges:=False
    i = i + 1
    f = Dir
Loop

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

请尝试稍微调整一下您的代码(这是一块很好的鳕鱼 e)

Sub TextImporter2()
Dim f As String, flPath As String
Dim i As Long, j As Long
Dim ws As Worksheet

Application.DisplayAlerts = False
Application.ScreenUpdating = False

flPath = ThisWorkbook.Path & Application.PathSeparator
i = ThisWorkbook.Worksheets.Count
j = Application.Workbooks.Count

FileNames = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", MultiSelect:=True, Title:="Text Files to Open")
If VarType(FileNames) = vbBoolean Then
MsgBox "No Files Selected"
Exit Sub
End If

For Fno = LBound(FileNames) To UBound(FileNames)
    Workbooks.OpenText FileNames(Fno), _
        StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True, _
        Space:=False, Other:=False, TrailingMinusNumbers:=True
    f = ActiveWorkbook.Name
    Workbooks(j + 1).Worksheets(1).Copy After:=ThisWorkbook.Worksheets(i)
    ThisWorkbook.Worksheets(i + 1).Name = Left(f, Len(f) - 4)
    Workbooks(j + 1).Close SaveChanges:=False
    i = i + 1
Next Fno

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

如果能帮助您,将感到高兴。但是,您可能在命名新添加的工作表并添加预防措施之前,请检查工作表名称是否存在。