允许用户选择要导入的文本文件

时间:2018-06-13 08:52:25

标签: excel vba

我尝试创建VBA宏以允许用户选择文本文件并将其导入Excel电子表格,但我一直收到错误1004

这是我的代码

Sub SelectFile()

Dim fName As String

fName = Application.GetOpenFilename()
If fName = False Then Exit Sub

Sheets("Import sheet").Select
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT; " & fName, Destination:=Range("$A$1"))
    .Name = "Example"
    .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 = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = True
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
End Sub

1 个答案:

答案 0 :(得分:0)

这样做,我对你的代码做了一些修改。

Sub SelectFile()

Dim fName As Variant

fName = Application.GetOpenFilename("txtfiles (*.txt), *.txt")
If fName = False Then
MsgBox "No File Was Selected"
Exit Sub
End If

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & fName, Destination:=Range("$A$1"))
.Name = "Example"
.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 = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
 End With
 End Sub