Excel 正在尝试为FileDialog定义设置路径

Excel 正在尝试为FileDialog定义设置路径,excel,vba,Excel,Vba,您好,我正在尝试通过FileDialog导入一个.txt文件,使用以下代码利用查询表。我的问题是我无法定义FileDialog显示的路径,它只是打开了generic Documents\Excel文件夹。如何定义此对话框打开的路径?任何帮助都将不胜感激 Sub ImportTextFile() Dim fName As FileDialog, LastRow As Long Set fName = Application.FileDialog(msoFileDialogOpen) fName.

您好,我正在尝试通过FileDialog导入一个.txt文件,使用以下代码利用查询表。我的问题是我无法定义FileDialog显示的路径,它只是打开了generic Documents\Excel文件夹。如何定义此对话框打开的路径?任何帮助都将不胜感激

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

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

我认为您的错误是因为您没有在查询连接字符串中指定文件和文件夹路径

引用语法是

With ActiveSheet.QueryTables.Add(Connection:="TEXT;C:\Test.TXT", Destination:=Range("$A$1"))
        ... Blah
End With
你有

连接:=文本;&fName其中fName是

"\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC  Web RH\2017\" 
i、 e.没有关联的文件名

如果使用filedialog对象 Application.FileDialogmsoFileDialogFilePicker您可以收集所选文件并将其放入变量中

例如,FileName=.SelectedItems1


您能验证InitialFileName中的路径吗?根据这一点,只要路径有效,指定InitialFileName就可以工作。为了澄清:我没有尝试导入预定义的文件,我只想通过FileDalog打开一个文件夹,然后让用户选择要导入的文件,这是一个具有不同名称的文本文件,但不知道是否有帮助。顺便说一句,我收到以下错误消息:Excel找不到用于刷新此外部数据区域的文本文件。请检查以确保此文本文件未被移动或重命名,然后重试刷新。'是否尝试在查询中使用folderpath而不添加文件名?此处连接:=TEXT;&fNameHi这似乎是一个很好的观点,但是我故意不想指定一个文件,只需要打开文件夹,用户选择在该文件夹中找到的文本文件。文本文件本身有不同的名称,无法预定义。我可以这样做fName.InitialFileName=\\olscmesf003\gcm\u emea\TCU\u REPORTS\APPS\REPORTS\Regional\Pointsec for PC Web RH\2017\test\test\*WebRHLogs*但我得到的类型不匹配,我可以定义要导入的文件的一部分,其中包含*WebRHLogs*,然后放弃文件选择。InitialFileName正在将默认文件夹设置为在处打开。filedialog对象有一个属性。SelectedItems用于捕获随后选定的文件。如果您尚未启用multiselect,则.SelectedItems1将捕获所做的选择,即文件名。哦,天哪,我知道我很痛苦,但我就是不明白。你能根据你的建议修改我的代码来更新你的答案吗?我尝试将Filename=.SelectedItems1并将fName重命名为fPath,但没有效果。文件名如下:WebRHLogs-20171207-10235.txt,其中日期不同,最后的5位数字是随机生成的。但是,周一周末有三个文件,因此有时需要单独导入/处理多个文件。
Sub Main()
'https://analysistabs.com/excel-vba/folders-file-handling/ ''example layout taken from here.

    Dim fileName As String
    Dim fileChosen As Long
    Dim lastRow As Long

    'Declare a variable as a FileDialog object.
    Dim fd As FileDialog

    'Create a FileDialog object as a File Picker dialog box. This allows you to capture the selected item.
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    'Use a With...End With block to reference the FileDialog object.
    With fd

         'Set initial folder to open to
        .InitialFileName = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC  Web RH\2017\"

        'Set the Folder View
        .InitialView = msoFileDialogViewSmallIcons

        'Set the caption of the dialog box,
        .Title = "Please select a WebRHLog file"

        'Allow only one file to be selected
        .AllowMultiSelect = False

        'Set the filter
        .Filters.Clear
        .Filters.Add "Text files", "*.txt"   'Not sure anything other than extension can be used as filter

        fileChosen = .Show

        If fileChosen <> -1 Then

           'No file selected/ Clicked on CANCEL
            MsgBox "No file selected"
            Exit Sub

        Else
           'capture name and complete path of file chosen
           fileName = .SelectedItems(1)

        End If

    End With

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

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fileName, _
        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