+ Reply to Thread
Results 1 to 3 of 3

Browsing to open a file in VBA

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    04-13-2010
    Location
    England
    MS-Off Ver
    Office 2016 365
    Posts
    211

    Smile Browsing to open a file in VBA

    Hi,

    I am very, VERY new to VBA so apologies if this is general knowledge.

    I am writing a macro that takes a dump of data in a text file, converts it to columns in excel and copies it to an Access Database.

    My code for opening the text file is simply

    TxtFileName = "C:\Users\7092\Desktop\Current Work\sqlexec.txt"
    Workbooks.OpenText Filename:=TxtFileName, Origin:=437, StartRow:=1, 
    DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, 
    ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, 
    Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1)), 
    DecimalSeparator:=".", ThousandsSeparator:=",", TrailingMinusNumbers:=True
    However, what i would like is for the user to be able to browse to find the text file and if it isn't too much trouble, for a warning to be presented if they try to choose a file that isn't a txt file.

    Thanks in advance for any help you can give me.

    J

  2. #2
    Valued Forum Contributor StevenM's Avatar
    Join Date
    03-23-2008
    Location
    New Lenox, IL USA
    MS-Off Ver
    2007
    Posts
    910

    Re: Browsing to open a file in VBA

    Add to your module:

    Function GetTextFile(sPath) As String
        ChDir sPath
        GetTextFile = Application.GetOpenFilename( _
            FileFilter:="Text Files (*.txt), *.txt,", _
            FilterIndex:=1, _
            Title:="Select A Text File")
    End Function
    Then change:

    TxtFileName = "C:\Users\7092\Desktop\Current Work\sqlexec.txt"
    to:

    TxtFileName = GetTextFile("C:\Users\7092\Desktop\Current Work")
    Then perhaps something like:

    If Len(TxtFileName) then
        If Right$(TxtFileName, 4) <> ".txt" Then
            Msgbox "You must select a text file!"
            Exit Sub
        End If
    Else
        Exit Sub
    End If

  3. #3
    Forum Contributor
    Join Date
    04-13-2010
    Location
    England
    MS-Off Ver
    Office 2016 365
    Posts
    211

    Re: Browsing to open a file in VBA

    Thanks that seems to work great!

    Ta very much

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1