Create Hyperlink to Cell in Another Workbook/CSV VBA - 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"")"
'^^^

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

VBS GetObject will not bind to saved workbooks

I'm trying to write a script which will switch to a specific excel workbook and enter keys, however, the script will only run if the workbook which is being referenced is unsaved.
For example:
If I open a new excel workbook which creates a new workbook named "Book1"; the following works:
Set xl = GetObject("Book1").Application
If I run the above when the workbook has been saved, even if the name remains the same, the above results in the following error: (0x800401E4).
Is anyone aware of this being a problem, or can anyone point out what I'm doing wrong? I'd guess the error has something to do with the object name being different from the actual file name, so when excel creates the default workbook the code works because the name of the instance is "Book1" whereas the saved "Book1" is assigned another object name when saved?
I wasn't sure if I needed to close this question as answered, however, it seems that https://stackoverflow.com/users/4088852/comintern has resolved the issue.
It needs to be the full path -
GetObject("C:\Users\Me\Documents\Book1.xlsm").
Thanks,

Programmatically Update Linked Named Range of excel object in MS Word (2007)

First question, excuse me if this has already been solved, but I've searched thoroughly and cannot find an answer:
I have linked several named ranges into a word document. This word doc (and the related excel workbook with named ranges) is a template: it's for a coworker who will make many copies of these templates (of both the word doc and the excel workbook).
I would like to include a command button in the word doc that, when clicked, will update the sources for the linked named ranges. Specifically, I want it to set the workbook with the same name as the worddoc, as the source.
The issue is that it does not like the named range I have entered. I get the:
Run-time error '6083': Objects in this document contain links to files that cannot be found. The linked information will not be updated.`
However, I have quadrupled-checked my excel doc, the named range exists. AND, when I hit Alt+F9 in word, I clearly see the link contains the named range!
{LINK Excel.Sheet.8 C:\Users\Marc\Documents\WIP_SSS.xlsm CED \a \p}
Here is my code:
Public Sub ChangeSource()
Dim filename As Variant
Dim fieldcount As Integer
Dim x As Integer
filename = Left(Application.ActiveDocument.Name, Len(Application.ActiveDocument.Name) - 4) & "xlsm"
fieldcount = ActiveDocument.Fields.Count
For x = 1 To fieldcount
'Debug.Print ActiveDocument.Fields(x).Type
If ActiveDocument.Fields(x).Type = 56 Then
ActiveDocument.Fields(x).LinkFormat.SourceFullName = ActiveDocument.Path & "\" & _
filename & "!CED"
End If
Next x
End Sub
If I don't enter the named range at all, the macro works, but it embeds the entire excel worksheet (which I do not want it to do). Any ideas on how/ why it is not liking the named range?
Thanks,
Marc
UPDATE:
With help from Bibadia, I found a solution; in addition, I want to document some strange behavior exhibited by Word VBA:
First off, the solution code:
Public Sub ChangeSource()
Dim filename As Variant
Dim fieldcount As Integer
Dim x As Integer
filename = ThisDocument.Path & "\" & Left(Application.ActiveDocument.Name, Len(Application.ActiveDocument.Name) - 4) & "xlsm"
fieldcount = ActiveDocument.Fields.Count
For x = 1 To fieldcount
On Error Resume Next
If ActiveDocument.Fields(x).Type = 56 Then
ActiveDocument.Fields(x).Delete
End If
Next x
ActiveDocument.Bookmarks("R1").Range.InlineShapes.AddOLEObject filename:=filename & "!Range1", LinkToFile:=True
End Sub
I first deleted all type 56 fields (linked object, or more technically, "wdfieldlinked"). Then, I added OLEObjects at pre-set bookmark locations.
Interestingly, just as Bibadia noted, the key was to input the LinkToFile:=True code. It seems Word will not accept the object if it is embedded: if I remove that line, I get the error Word Cannot obtain the data for the C:\...\document!NamedRange link.
Finally, I found one other odd behavior: When trying to simply replace the link, using this code,
ActiveDocument.Fields(1).LinkFormat.SourceFullName = filepath+name & _
"!CED" 'that is the named range
it would work once, when I changed both the word document's and the excel workbook's filenames (see original message for context). So, when the new filepath+name DID NOT match the existing filepath+name, Word VBA accepted the change. However, once initially updated, if I tried to run the macro again, I would get:
run-time error '6083': Objects in this document contain links to files that cannot be found. The linked information will not be updated.
I would get this error even if I changed the named range to another named range in the same worksheet (and obviously same workbook). So it appears that Word VBA does not like "updating" filepath+name when the filepath+name does not change.
Just so anyone who didn't know (like me) now knows. Sorry for the long update, I just wanted to be thorough.
I am not completely sure of this, but it is a little too long for a comment.
As far as I know, you can only set LinkFormat.FullSourceName to the name of a file, not a fullname + subset name, which is what you are trying to do when appending the "!CED". Although you can read the subset name (CED) from OleFormat.Label, you can't modify it as it's a read-only property.
So if you actually need to modify the subset name (CED), AFAICS the only way to do it is to delete and reinsert the LINK field. If you reinsert using Fields.Add, you just specify the text of the field, so you can get the file name and Subset name right. What is slightly confusing is that if you insert a LINK using InlineShapes.AddOleObject, you can specify fullname+subset name in exactly the way that you are trying to do in your code.
However, I do not think you are trying to modify the Subset name. So let's assume that you already have a LINK field along the lines of
{ LINK Excel.SheetMacroEnabled.12 "the full pathname of a .xlsm file" CED \a f 0 \p }
Word will only be able to update that link if the path+filename is valid (i.e. there's a .xlsm at that location, the workbook has a Range Name called CED, and the Range Name is in the first Sheet. Otherwise, you have to specify a Sheet name as well, e.g.
{ LINK Excel.SheetMacroEnabled.12 "the full pathname of a .xlsm file" Sheet2!CED \a f 0 \p }
It's just a guess, but if your code is trying to connect to a Workbook where the range defined by CED is not in the first sheet, you would see the error you describe.
Further, the scope of the CED Range Name has to be either "workbook" or the name of the first sheet. Otherwise, if the scope is the first sheet but the range is actually in another sheet, or vice versa, I do not think Word can make the connection whatever subset name you provide (my guess is that Word never really caught up with Excel after Excel introduced multi-sheet workbooks).
If CED can reference sheets other than the first one, I think you will probably have to use the Excel object model to discover which sheet its Range is in, construct the appropriate Subset name, and delete/re-insert the LINK field.

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

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

change worksheet name, a difficult one

When I use excel to open a .txt file (a notepad file), the worksheet name is the file name of the notepad file that was opened by default. Therefore, the sheet name will be different when open a different notepad file. Downstream code need this worksheet name be a fixed one. Is there anyway to make change the sheet name to a fixed name such as "sheet1". By the way, codename can not be used, since the macro to use the data in the open file is not another workbook.
Thanks!
You don't need the codename not the worksheet name when you are opening .txt files from Excel. There will always be 1 sheet. So in your code you can always address that sheet as
wb.Sheets(1)
Where wb is the workbook object.
For your reference every .txt file that you open with VBA cannot have a common name unless you set it via code. And if you do that, you will have to still use wb.Sheets(1)
For example
wb.Sheets(1).Name = "Blah Blah"
Could you call your text file sheet1.txt? Would that solve your problem?
I am picturing that your macro opens the text file dynamically because you want to use excel's built in csv parsing. Perhaps sorting and filtering the data afterwards.
Siddarth gave you a good lead, but you shouldn't worry about the name or the sheet because as he said you have the worksheet object to use for your downstream code.
wb.Sheets(1)
Now, if you want to reference this sheet outside of the subroutine that you opened the file. Use a global variable for your
wb