简体   繁体   中英

getopenfilename VBA code on Excel2016

I have a VBA script to import txt file. It works well on Excel 2013. On excel 2016, getopenfilename does not support argument anymore (excel crash). It works when removing all arguments of getopenfilename()

Any idea ?

 Sub Import_TXT()
On Error GoTo Err1

With Sheets("Sheet2").QueryTables.Add(Connection:= _
    "TEXT;" & GetTXT, Destination:=Sheets("Sheet2").Range("A1"))
    .Name = "logexportdata"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlOverwriteCells
    .SavePassword = False
    .SaveData = False
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

Exit Sub

Err1:
MsgBox "Data not imported. Error: " & Err.Number & vbCrLf & Err.Description

End Sub

Function GetTXT() As String

Dim filename__path As Variant


'  Get the filename
  filename__path = Application.GetOpenFilename(FileFilter:="TXT (*.txt), *.txt", Title:="Select txt file")

If filename__path = False Then Exit Function

GetTXT = filename__path
End Function

The solution I found is to replace by

With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Text file", "*.txt", 1
.FilterIndex = 1
.Title = "Select txt file"
.Show
filename__path = .SelectedItems(1)
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM