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

我一直在使用宏将多个.txt文件导入到我的活动excel工作簿中(请参阅下文).我希望以允许我选择要导入的文件以及以相同方式运行的方式来更改它.我尝试使用“Application.GetOpenFilename(FileFilter:=”Text Files(.txt),. txt“,MultiSelect:= True,Title:=”Text Files to Open“)”,但我收到类型不匹配错误.

我觉得这应该不是大问题,但我似乎无法解决这个问题.

任何建议都非常感谢.

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

最佳答案 请尝试你的代码(这是一个很好的代码)调整一点

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

如果能帮到你,我们会很高兴.但是,您可以在命名新添加的工作表并添加预防措施之前检查工作表名称是否存在.

点赞