gpt4 book ai didi

excel - 如何修改此代码以通过 FileDialog 导入文本文件?

转载 作者:行者123 更新时间:2023-12-02 17:43:44 24 4
gpt4 key购买 nike

您好,我正在尝试从设置路径中基于 FileDialog 的文件夹导入文本文件?我有一个导入文本文件的代码,但它只打开一个通用的 C:\\ 路径,我应该如何修改下面的代码才能打开指定路径的文件夹?

Sub ImportTextFile()
Dim fName As String, LastRow As Long

fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fName = "False" Then Exit Sub

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
Destination:=Range("A" & LastRow))
.Name = "sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierNone
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "" & Chr(10) & ""
.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, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub

任何帮助将不胜感激!

我对代码的开头进行了以下更改,但现在我收到“1004 应用程序定义的错误”

Sub ImportTextFile()
Dim fName As FileDialog, LastRow As Long

Set fName = Application.FileDialog(msoFileDialogOpen)
fName.InitialFileName = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC Web RH\2017\"
If fName = "False" Then Exit Sub

最佳答案

使用ChDir在打开文件之前可能会有所帮助。我会发表评论,但没有足够的声誉,所以在这里发帖。

例如

Sub ImportTextFile()
ChDir "C:/yourpath/folder/etc"
Dim fName As String, LastRow As Long
....

关于excel - 如何修改此代码以通过 FileDialog 导入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com