首页 文章

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

提问于
浏览
0

我正在尝试创建一个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

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

    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
    

相关问题