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

标签 excel vba

您好,我正在尝试从设置路径中基于 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/

相关文章:

excel - 用新图像替换现有图像

excel - 将 MIN/MAX 应用到数组的 LET 函数的奇怪行为

excel - 根据不同的列数据范围隐藏行

excel - 如何从另一张表中获取精确匹配的数据?

vba - 主键违规会触发警告,但不会触发错误处理程序

oracle - 查询表错误

vba - Excel 2007 VBA 宏逐行读取文本文件如何停止逗号 (,) 分隔

java - 如何使用 POI java 将多个工作表添加到同一工作簿?

excel - 动态搜索 ListObject 之间的缺失值

PHP制作实时股票交易应用程序