Import text file name

BernieRS

New Member
Joined
Jan 30, 2004
Messages
39
I used the wizard to import data from a text file and set the External Data Range Properties for saving the query, prompting for file name on refresh, and filling down formulas, etc. Is there some way of capturing the name of the file last imported as the source of the current data for displaying in a cell on the sheet? I use a button macro containing Range("B4").Select, Selection.QueryTable.refresh BackgroundQuery:=False to import the data. Thanks. --Bernie
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
This might do. It looks for "FROM" in the Sql string. May need to adapt further for anything after the file name :-
Code:
    Dim MySql As String
    Dim MyFile As String
    MySql = ActiveSheet.QueryTables(1).Sql
    x = InStr(1, MySql, "FROM", vbTextCompare)
    MyFile = Right(MySql, Len(MySql) - x - 5)
    MsgBox (MyFile)
 
Upvote 0
Thanks for the help, Brian, but I decided to have more control over the file selection by using:

f = Application.GetOpenFilename(FileFilter:="Text Files (*.txt) , *.txt",Title:="Open text file to import the data")
If f <> False Then
With ActiveSheet.QueryTables("Data")
.Connection = "TEXT;" & f
.TextFileStartRow = 3
.Refresh BackgroundQuery:=False
End With
Range("A34").Value = f

Instead of activating the wizard produced query via:

Range("B4").Select
Selection.QueryTable.Refresh BackgroundQuery:=False
 
Upvote 0

Forum statistics

Threads
1,214,653
Messages
6,120,751
Members
448,989
Latest member
mariah3

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top