Importing Based on a Partial File Name

by Allen Wyatt
(last updated September 24, 2016)

2

Ira receives a weekly text-delimited file that he imports into Excel by using a macro. The file name was always the same each week, so Ira was able to embed it into the macro; this made importing very easy. Recently the vendor's new system started changing the file name each week, but the first 12 characters always remain the same. Ira wonders how he can code the macro to import this text file without needing to modify the file name each week.

There are a few ways you can approach this problem, and all of them may mean some extensive recoding of your macro. The method you choose should depend on how you want to do your work each week. For instance, let's say that you know the directory in which the incoming file is stored, what the base 12 characters are for the filename, and the filename extension. With that information, you could simply prompt the user to provide the suffix for the filename, in this manner:

Sub OpenImportFile()
    Dim sFileName As String
    Dim sBase As String
    Dim sSuffix As String
    Dim sExt As String

    sBase = "c:\MyDirectory\First12Chars"
    sExt = ".csv"
    sSuffix = InputBox("Enter suffix for filename")

    sFileName = sBase & sSuffix & sExt
    Workbooks.Open Filename:=sFileName
End Sub

You can, obviously, change the base and extension as you desire. This example assumes that you are importing a CSV file, which should open in Excel just fine.

If you are simply placing a group of files into a folder and you want to open all of them, then the code becomes a bit quicker to run because you don't need to get user input.

Sub OpenImportFiles()
    Dim sFileName As String
    Dim sBase As String
    Dim sExt As String

    sBase = "c:\MyDirectory\First12Chars"
    sExt = ".csv"

    sFileName = Dir(sBase & "*" & sExt)
    If sFileName = "" Then
        MsgBox "No Files Found"
    Else
        Do While sFileName > ""
            Workbooks.Open Filename:=sFileName
            sFileName = Dir
        Loop
    End If
End Sub

This approach opens all the CSV files in the folder; to open a different type of file, just change what is stored in the sExt variable. One thing to remember is that since all the CSV files in the folder are opened, that means it may open import files from previous weeks. (This may or may not be what you want.)

Everything presented in this tip so far assumes that when you "import" a file, all you want to do is open the file so you can work with it. That may not be the case; you may want your macro to process the import file in some way and do something with it. That functionality may already be in your older macro, so all you need to do is change how the import file is identified. If this is the case, the code you use can be adapted from the code already presented in this tip.

Another way to grab the data out of a text file and stuff it into a workbook is to use the OpenText method, as shown in this example code.:

Sub OpenImportFile()
    Dim sFileName As String
    Dim sBase As String
    Dim sExt As String

    sBase = "c:\MyDirectory\First12Chars"
    sExt = ".csv"
    sFileName = sBase & "*" & ".txt"

    Workbooks.OpenText Filename:=sFileName, Origin:= _
      xlMSDOS, StartRow:=1, DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, Tab:=True, _
      Semicolon:=False, Comma:= False, Space:=False, _
      Other:=False, FieldInfo:=Array(1, 1), _
      TrailingMinusNumbers:=True
End Sub

A full exploration of what the OpenText method does is beyond the scope of this tip, but the result is that all of the delimited text files that begin with the base 12 characters should be opened in your workbooks. You can modify how the method works by changing the parameters. You'll want to pay particular attention to the parameters used to specify what delimiter character should be used.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (13472) applies to Microsoft Excel 2007, 2010, 2013, and 2016.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Saving and Closing All Open Documents

Want to close or save all your documents at the same time? This trick does it for you.

Discover More

Dealing with Large Numbers of Seconds

When adding values to a time to calculate a new time, you may naturally choose to use the TIME function. This can cause some ...

Discover More

Heavy-Duty Footnotes

Word allows you to add footnotes to a document, but they are rather straightforward and simple in their application. If you ...

Discover More

Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!

More ExcelTips (ribbon)

Deleting Old Data from a Worksheet

If you keep on-going data in a worksheet, some of your data—over time—may need to be deleted. If you have an ...

Discover More

Determining Differences Between Dates

Macros are often used to process the data in a worksheet. If that data includes dates that need to be processed, you'll ...

Discover More

Editing Macros

Even if you do nothing but record macros, sooner or later you will have a need to edit what you record. Here's how to get to ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 7 + 6?

2016-09-25 14:03:35

Mike H

Just been looking at the above code and sFileName just kept coming up blank. Then I noticed for this to work I needed "" at the end of sbase i.e.

sBase = "c:MyDirectoryFirst12Chars"

as without the final backslash this does not work.

Please could you check.


2016-09-25 04:11:06

Thomas Papavasiliou

Another quite useful approach is to make the macro ask for the files to open.
The relative code is:

FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Microsoft Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, _
Title:="Select Files to Merge. Shift+click or Ctrl+click for multiple selections")

If TypeName(FilesToOpen) = "Boolean" Then
msg = "No Files were selected. Macro ends! "
ttl = "Oops..."
MsgBox msg, vbInformation, ttl
Exit Sub
End If

that can be inserted in your macro and let you choose the files.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.