Excel 允许用户选择要导入的文本文件
我试图创建一个VBA宏,以允许用户选择一个文本文件并将其导入excel电子表格,但我一直收到一个错误1004 这是我的密码Excel 允许用户选择要导入的文本文件,excel,vba,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.A
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
这样就可以了,我对你的代码做了一些修改
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