简体   繁体   中英

Excel VBA Open 1 CSV file

Using Excel 2010, I am trying to add a code that will open up the file select window for the user to select the CSV file he wants to open.

My code is below:

Dim OpenThisFile
OpenThisFile = Application.GetOpenFilename

This was just taken from one of my old VBA files, this has worked before. Currently though, when the VBA reads the 2nd line it opens up the file select window but as soon as I select a CSV file and hit OPEN it gives the error Application-Defined or Object-Defined Error

GetOpenFilename will return the full filespec as a String variable. You can parse it like:

Sub qwerty()
    Dim f As String, Path As String, _
        FileName As String, FileType As String

    f = Application.GetOpenFilename()
    MsgBox f

    ary = Split(f, "\")
    bry = Split(ary(UBound(ary)), ".")
    ary(UBound(ary)) = ""
    Path = Join(ary, "\")
    FileName = bry(0)
    FileType = bry(1)

    Range("A1") = Path
    Range("A2") = FileName
    Range("A3") = FileType
End Sub

在此处输入图片说明

and if you want to pre-select the path and filetype then:

Sub qwerty2()
    Dim f As String, Path As String, _
        FileName As String, FileType As String

    ChDir "C:\TestFolder"
    f = Application.GetOpenFilename(FileFilter:="Text Files (*.csv), *.csv")
    MsgBox f

    ary = Split(f, "\")
    bry = Split(ary(UBound(ary)), ".")
    ary(UBound(ary)) = ""
    Path = Join(ary, "\")
    FileName = bry(0)
    FileType = bry(1)

    Range("A1") = Path
    Range("A2") = FileName
    Range("A3") = FileType
End Sub

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