How to get File Name of External File for an Existing Connections - Excel - vba

I import an External text file (.csv) to my excel worksheet named "SourceData".
The connection is called "Data". Every time I refresh my workbook, excel will ask me to choose my source file. My source files same data structure, and they are automatically generated by other database:
REPL_STATS_010314130000.CSV
REPL_STATS_030314060001.CSV
....
My question is:
How can I get the file name of my external csv file that currently imported to my worksheet "SourceData" so when I refresh the connection, This name is displayed in a cell (for example A1) in another sheet named "Summary"
For example: after I click refresh all, choosing file "REPL_STATS_010314130000.CSV" to update my data source, then cell A1 will display "REPL_STATS_010314130000.CSV"
I try to search for a solution a few days already, but I can't get it work.
Can you suggest form VBA code that can get this information?
Thank you in advance!

Thanks to Tim Williams suggestion I write the following code, and put this code in Sheet1(SourceData):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ConSource As String
ConSource = Worksheets("SourceData").QueryTables("Data").Connection
Worksheets("Summary").Range("A1").Value = "Source: " & Right(ConSource, Len(ConSource) - InStrRev(ConSource, "\"))
ConSource = ""
End Sub

Related

How can I change the name of another Excel workbook I'm referencing in my code by entering the file name into a cell?

Here's what I'm trying to do.
My Excel workbook, InspectionFormTemplate3.4.xlsm, exists as a template to copy over data from various other workbooks that have a totally different format. The code works for copying the data over, but I have 1500 reports to convert and every time I have to manually go into my code and ctrl+f replace all instances it references the report to be converted. Instead, I enter data into a cell (S50) and tried replacing the referenced file name with a variable I named oldfilename. That is what gives me an error, and that's what I'm stuck on.
I've looked around for hours in order to find something that does what I'm trying to do, but I have no real experience with VBA at all. I think this is probably just a simple syntax error.
So, here's what I tried so far with my current code.
Private Sub ConvertButton_Click()
Dim oldfilename As String
oldfilename = Range("S50")
'Name of bldg and date
Workbooks("InspectionFormTemplate2018.3.4.xlsm").Worksheets("COVER PAGE").Range("C9").Value = Workbooks("ReporttoConvert.xls").Worksheets("Cover Page").Range("B5").Value
Obviously here, "ReporttoConvert" is a placeholder for an actual workbook name. It works when I manually insert file names, but I need it to look more like this instead:
Workbooks("oldfilename")
in order for it to change to whatever I input as the file name in cell S50. I'm sure this is probably pretty simple, but I have no clue what this would be called or how to do it.
Try this, your macro enabled workbook should be saved in the same folder as the other workbooks, else you will have to change 'ThisWorkbook.path...
Dim OpenWb As String
OpenWb = ThisWorkbook.Worksheets("COVER PAGE").Range("S50").Value
Workbooks.Open Filename:=ThisWorkbook.Path & "\" & OpenWb
ThisWorkbook.Worksheets("COVER PAGE").Range("C9").Value = Workbooks(OpenWb).Worksheets("Cover Page").Range("B5").Value

Excel VBA macro - Change link name

I have a excel macro routine that I need to prep a file for another routine which is run daily. This prepping involves changes the links of t-1 file to a t0 file.
The code I usually do is:
ActiveWorkbook.ChangeLink Name:= _
"file path", NewName:=new_file_path, Type:=xlExcelLinks
My trouble now is that for this particular routine the file path to be changed to a new routine is not always the same, thus I would need a way to automatize finding out what are the current links to replace them all. The new file path I now because it is the worksheet that is calling this routine and opening this file, so first thing I do Is
new_file_path = "C:\...."& ActiveWorkbook.Name & ".xlsm"
What would help me is if there is a trick to replace all links for a new one, without the need to say the name/path of the old links. Does any one know?
Thanks
To change all the excel links in a workbook try this procedure:
Sub WbThs_ChangeLink_Excel()
Dim wbTrg As Workbook
Dim sLinkNew As String
Dim aLinks As Variant, vLink As Variant
sLinkNew = "##VBA Links Replace - Target 3.xlsb" 'Change as required
Set wbTrg = ThisWorkbook 'Change as required
Rem Set array with all excel links
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
Rem Replace each excel Link
If Not IsEmpty(aLinks) Then
For Each vLink In aLinks
wbTrg.ChangeLink Name:=vLink, NewName:=sLinkNew, Type:=xlExcelLinks
Next: End If
End Sub
See the following pages for additional information on the resources used:
Workbook.ChangeLink Method (Excel)
Workbook.LinkSources Method (Excel)
XlLink Enumeration (Excel)

Create Hyperlink to Cell in Another Workbook/CSV VBA

I'm currently working on a script in WorkbookA that notifies of a change in another Workbook (WorkbookB). I would like to add the functionality of being taken to that Workbook if the user would like to see the change. Currently, I'm running the code:
SelRangeA(iRow, 2) = "=HYPERLINK(""[C:\..\WorkbookB.csv]Sheet1!B4"",""CLICK HERE"")"
Which displays the proper Hyperlink in the spreadsheet : Click Here with contents:
=HYPERLINK("[C:\..\WorkbookB.csv]Sheet1!B4","CLICK HERE")
However when I follow the link, it opens the requested Workbook with an error:
Reference is not valid.
Any insight on how to properly reference the required cell? Thanks!
A CSV file won't contain a "Sheet1". The "sheet" name is derived from the name of the file.
So your code needs to be:
=HYPERLINK("[C:\..\WorkbookB.csv]'" & filename & "'!B4","CLICK HERE")
where filename has been set to the base part of the CSV file's filename (i.e. it needs to equate to "WorkbookB" in your example).
One way to do this is to define a name (Formulas->Name Manager) whenever certain cells get changed. For example if the name was defined as "changedcell" you would set the hyperlink as follows:
=HYPERLINK("[C:..\WorkbookB.csv#changedcell]","CLICK HERE")
Just make sure the scope of the name is set to full workbook if there are multiple worksheets.
If the link is in another workbook and you want Excel to open it if it isn't already open, you need to specify both the address and the sub-address (kind of like an anchor in an HTML link):
SelRangeA(iRow, 2) = "=HYPERLINK(""C:\Foo.xlsx#[C:\Foo.xlsx]Sheet1!A1"")"
EDIT: Note that for a .csv file, the worksheet name will default to the file name on open:
SelRangeA(iRow, 2) = "=HYPERLINK(""C:\Foo.csv#[C:\Foo.csv]Foo!A1"")"
'^^^

getting vales from different file locations contained in cells Excel

So I'm trying to create a tracking file in Excel and in cell M5, I have a file location which links to a supporting document and as such, contains some duplicated information so I want to try and pull certain fields (B8 in this example) from the external files referenced in M5.
I have tried =([M5]Sheet1!B8) which works to a degree but this brings up a dialogue box and I have to select the file location manually which is too manual for the purpose.
I have also looked into using the INDIRECT function but can't guarantee that both files will be open at the same time, so would prefer another option if possible.
Any suggestions would be hugely appreciated!!
Here is formula you can use to get individual cell values from a closed workbook.
It is a User Defined Function (UDF) and you call it like this:
=GetClosedCell(A3,B3,C3)
The 1st parameter is the workbook path and name.
The 2nd parameter is the worksheet name.
The 3rd parameter is the address of the cell.
Place this function in a standard code module:
Public Function GetClosedCell(ByVal FileSpec$, ByVal SheetName$, ByVal RangeAddress$)
Const CNX = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[];Extended Properties=""Excel 12.0;imex=1;hdr=no;"""
Const QRY = "SELECT * FROM [.$|:|]"
On Error GoTo errorh
RangeAddress = Range(RangeAddress)(1, 1).Address(0, 0)
With CreateObject("adodb.recordset")
.Open Replace(Replace(QRY, "|", RangeAddress), ".", SheetName), Replace(CNX, "[]", FileSpec)
GetClosedCell = .Fields(0)
End With
Exit Function
errorh:
GetClosedCell = "ERROR: " & Err & " " & Err.Description
End Function
Here is how it would look on a worksheet:
It is possible to grab data from an external file without opening it. For Excel to get a data item, it needs to know:
the file location
the name of the file within that location
the name of the worksheet within that file
the address of the cell within that worksheet
We enter the required info into some cell, say cell C3 in a very specific format:
'C:\TestFolder\[ABC.xls]xxx'!R9C2
note the single quotes!
then running this short macro:
Public Sub GrabData()
Dim r1 As Range, r2 As Range
Set r1 = Range("C3")
Set r2 = Range("C4")
r2.Value = ExecuteExcel4Macro(r1.Value)
End Sub
will retrieve the data and place it in cell C4
Macros are very easy to install and use:
ALT-F11 brings up the VBE window
ALT-I
ALT-M opens a fresh module
paste the stuff in and close the VBE window
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE window as above
clear the code out
close the VBE window
To use the macro from Excel:
ALT-F8
Select the macro
Touch RUN
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
Macros must be enabled for this to work!

Calling a function from another Excel workbook

I've got a pile of data in one worksheet that I am trying to save to individual workbooks based on values in several columns. The approach I am taking (for better or worse!) is to copy the relevant worksheet (and macros) to a new workbook, save it with an appropriate name (let's say temp.xlsx), and then to cleanse the data in that new workbook by deleting irrelevant rows (function called deleteInfo). This all has to be done without altering the original workbook, as per company policy.
I can copy the stuff over no problem, but I'm having serious issues calling macros in the new workbook then.
I have tried:
Application.Run "'temp.xlsx'!deleteInfo"
ActiveWorkbook.Application.Run deleteInfo
Application.Run ("'C:\user\.....\temp.xlsx'!deleteInfo")
But none have worked.
For the task like this you should consider creating an Excel add-in (file extension .xla) containing VBA macros while keeping the regular Workbooks with data macro-free (extension .xls or .xlsx). More details in Microsoft online article: https://support.office.com/en-ca/article/Add-or-remove-add-ins-0af570c4-5cf3-4fa9-9b88-403625a0b460
Hope this may help.
Solved this issue by exporting the module in which the macro was saved, copying the original workbook and importing it into the new workbook. pathName was defined in previous module to this as the path to the original file's folder (pathName = ActiveWorkbook.Path)
Sub exportMacro(ByVal pathName As String)
'Export the macro to save as .bas file
On Error Resume Next
Kill pathName & "\Module6.bas" 'Delete previously exported file
On Error GoTo 0
ActiveWorkbook.VBProject.VBComponents("Module6").Export pathName & "\Module6.bas"
End Sub
Sub importMacro(ByVal pathName As String)
'import the macro to a new workbook
ActiveWorkbook.VBProject.VBComponents.Import pathName & "\Module6.bas"
End Sub