I am trying to change an excel workbook link, but by constructing a new workbook link using dates in cells (the naming convention is always the same, except that the date changes)
I know that to change an excel workbook link (using VBA), all I have to do is:
ActiveWorkbook.ChangeLink "c:\excel\book1.xls", _
"c:\excel\book2.xls", xlExcelLinks
But what if I want to construct a new workbook link using different figures in cells?
This is what I have been trying:
ActiveWorkbook.ChangeLink "part of file name" & Range("N2") & ".xlsx"", _
"part of file name" & Range("N4") & ".xlsx"", xlExcelLinks
Range N2 is the previous week's date, and Range N4 is current week's dates.
But whenever I do this I get the following message "Compile error: Syntax error"
Any ideas on what I can do? Really want to be able to construct file name as it'll mean I can automate a LOT of what I do...lol
Thank you in advance for any guidance on this!
First, if you want to include " in string you must double it, so:
ActiveWorkbook.ChangeLink """part of file name" & Range("N2") & ".xlsx""", _
"""part of file name" & Range("N4") & ".xlsx""", xlExcelLinks
this was your error reason
Also you should refer to .Value property od Range object, and if cells you are using contains dates the safest way would be using Format(Range("N4").Value, "yyyymmdd")
Related
I am attempting to write code that will automate updating inventory spreadsheets for different vendors. I have run into a problem when it comes to saving the files as the vendors require different file types when uploading the inventory. So what I am needing is some code that will dynamically change the save as file type depending on the vendor.
What I have so far is a multi-select file dialogue which the user utilizes to select the spreadsheets they want to update. The VBA I have so far loops these selected templates which are opened, updated via formulas in the spreadsheet, and then saved in a different folder and named with the vendor name and the current date.
Here is the problem section of code I am working with:
CustomerWB.SaveAs Filename:="S:\Online Inventory Reports\" _
& Left(CustomerWB.Name, 6) _
& "\" _
& Left(CustomerWB.Name, 6) _
& " " _
& Format(Now(), "MM.DD.YY") _
& WorksheetFunction.Index(ThisWorkbook.Sheets(2).Range("B:B"),WorksheetFunction.Match(Left(CustomerWB.Name, 6),ThisWorkbook.Sheets(2).Range("A:A"),0)), _
FileFormat:=WorksheetFunction.Index(ThisWorkbook.Sheets(2).Range("C:C"),WorksheetFunction.Match(Left(CustomerWB.Name, 6),ThisWorkbook.Sheets(2).Range("A:A"),0))
I have debugged each piece of the code and it works up until I hit the Index(Match() sections.
The formulas are looking into a table which has the vendor IDs next to the required file type and type code. When run in the immediate window, these formulas produce the desired result. But when they are run in this code, an error is returned: Run-time error '1004': Method 'SaveAs' of Object '_Workbook' failed So it seemed like VBA didn't like the fact I was mixing in worksheet functions when trying to save the file.
So I moved the Index(Match()) sections into the spreadsheet and had the VBA populate a cell with the vendor name. Then assigned variables to the values of the cells which now returned the file type and type code. The new code looks like this:
CustomerWB.SaveAs Filename:="S:\Online Inventory Reports\" _
& Left(CustomerWB.Name, 6) _
& "\" _
& Left(CustomerWB.Name, 6) _
& " " _
& Format(Now(), "MM.DD.YY") _
& FileType, _
FileFormat:=TypeCode
But I get the same error. Any help would be much appreciated.
Turns out it was a simple error. I had the asterisk included in the file extension being returned (ex. *.xlsx). Upon removing the asterisk from the file extensions in the table, the code ran fine.
I want a method to create a hyperlink of some variable in excel macro.
My requirement is I have to capture a link in some variable for ex:
abc = InputBox("Enter the path")
now I want to use this abc as a parameter to a hyperlink function and create a hyperlink with name xyz.
Can you help me to solve this issue?
OK, here is the code. What it is doing is
1. Asking what URL you want
2. Storing the URL in a variable called URL
3. Going to Sheet 1, adding the hyperlink function to cell A5, linking it to the URL you input
4. Displaying the friendly name you give it in the code
Let me know if you have any questions | you will just need to modify the code for the URL you want or place the links where you want.
Tested and working. Please vote as answer :)
Sub CreateHyperLink()
Dim URL As String
URL = InputBox("Enter the link")
With Worksheets("Sheet1")
.Hyperlinks.Add Anchor:=.Range("A5"), _
Address:="http://www." & URL, _
TextToDisplay:="Google"
End With
End Sub
Use the HYPERLINK function:
=HYPERLINK(link_location, friendly_name)
Creates a shortcut or jump that opens a document stored on your hard drive, a network server, or on the Internet.
For example in macro code:
Worksheets("Sheet1").Range("A1").Formula = "=HYPERLINK(""" & link_destination & """,""" & link_text & """)"
Note the use of "" (two double quotes) in the VBA code to produce a single double quote in the cell formula.
I'm trying to use STRCONV vbPropercase to correct input in a macro that I use to copy data from one "input" worksheet to another. I have been able to assign specific variables to cells and then apply the STRCONV Propercase to the variable, but no change is made to the text in the cell when I do this. The code saves the file as a combination of the variable names, so I know that it makes the corrections there. How do I make the change appear in the cell and not just to the variable in the code?
Here is an excerpt from the code I'm using:
Dim Property As String
Dim Accnt As String
Property = Worksheets("Audit").Range("L6").Value
Property = StrConv(Property, vbProperCase)
Accnt = Worksheets("Audit").Range("L7").Value
ActiveWorkbook.saveas "D:\(username)\Documents\" & Accnt & " - " & Property & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
Just flip the assignment around:
Worksheets("Audit").Range("L6").Value = Property
I have an .xltm template spreadsheet that I'm wondering if I can get a macro to populate the "save as" file name based on cell data, is this possible?
There are over 50 people who will have this spreadsheet, it's more of a form, and we are trying to figure out a way to keep the filenames uniform. I know there is the ThisWorkbook.BeforeSave, but I'm not really having any luck there. I just need it to make a file named something like $A$1 R $B$1 T $B$3.xlsx
Any ideas on how to do this?
Sure.
Sub SaveMyWorkbook()
Dim strPath As String
Dim strFolderPath as String
strFolderPath = "C:\"
strPath = strFolderPath & _
Sheet1.Range("A1").Value & "R" & _
Sheet1.Range("B1").Value & "T" & _
Sheet1.Range("B3").Value & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strPath
End Sub
EDIT: After you clarified your question in your comment below, I can now safely say that the answer is: No, what you are asking is not possible.
What is possible is to put a big, fat command button on your sheet that says "Press me to save", and have that button call the above Sub. You can set a fixed folder, as in the example above, or have the user pick a folder using the FileDialog object (or the GetSaveAsFilename function, but then the user will be able to change the suggested filename, so less safe).
I've written a macro for Excel 2010 which indexes a folder for any containing files and subfolders. The purpose of this is to manage the extraction of a particular detail from a folder directory containing hundreds of files only some of which are Excel files and of those only some of which are relevant to this detail.
The macro provides a few basic details and hyperlinks to the files (including xls, doc, pdf etc). The vba code then inserts a cell formula to extract a single cell value from a particular location of the workbooks (without opening them) where there is an Excel file and produces a #Ref! error otherwise. Since the cell formula is created through FileItem.Path and text manipulation, the formula always references the "Summary" sheet as is appropriate for the meaningful files.
The problem is that the remaining Excel files do not have a worksheet with this name which prompts Excel to deliver a popup dialog 'Select Sheet' for the user to manually choose from the options. I need a way to manage this in the vba code. I can manage a number of potential outcomes including selecting OK to choose the 1st option every time, cancelling and ignoring the request, skipping those instances etc but I cannot have the macro repeatedly interrupted for user input.
I have tried inserting Application.DisplayAlerts = False at various points in the code but it doesn't prevent that dialog.
Any help/ suggestion is greatly appreciated.
Thanks
Edit
Originally I had:
Cells(r, 5).Formula = "='" & Left(File.Path, InStr(File.Path, File.Name) - 1) & "[" & File.Name & "]Summary'!$D$3"
...producing the following cell formula:
='C:\Documents and Settings\[TEST]Summary'!$D$3
It does indeed seem that you can't disable this "invalid reference" pop-up box (please correct me if I am wrong someone!), however, what you could do is generate your formula for the reference to your "Summary" sheet in VBA (as you are already doing), but evaluate it in VBA before pasting the actual formula so that if the formula returned fine without an error then paste it, otherwise you can perform some other action instead.
For example you have at the moment:
if FileType <> "XLS" then
myCellFormula = "#Ref!"
else
myCellFormula = "[<Target File Name>]Summary!A1"
endif
However, as you know trying to put in a reference to a non-existent sheet will cause excel to cough. What you can do is check for this error in VBA, for example:
On Error Resume Next
dim dummy as variant
if FileType <> "XLS" then
myCellFormula = "#Ref!"
else
dummy = Application.Range("[<Target File Name>]Summary!A1").Value
if not isempty(dummy) then
myCellFormula = "[<Target File Name>]Summary!A1"
else
<alternative action>
endif
endif
You could also do this with an error handler, it does depend on whether you wish to skip these non-existent references (so <alternative action> would be nothing).
Edit based on your latest reply, you could change the code to something like this:
On Error Resume Next
dim dummy as variant
dim targetFileFormula as string
dim lastSlashPos as long
lastSlashPos = InStrRev(fileitem.Path, "\", , vbBinaryCompare)
targetFileFormula = "'" & Left(fileitem.Path, lastSlashPos) & "[" & Right(fileitem.Path, Len(fileitem.Path) - lastSlashPos) & "]Summary'!$D$3"
if FileType <> "XLS" then
myCellFormula = "#Ref!"
else
dummy = Application.Range(targetFileFormula).Value
if not isempty(dummy) then
myCellFormula = targetFileFormula
else
<alternative action>
endif
endif
You can then tailor this to your needs.