Excel Hyperlinks change when I move spreadsheet - excel

I have a spreadsheet in which I add hyperlinks to files using vba as follows:
Sheet1.Cells.Hyperlinks.Add Sheet1.Cells(1, 1), objFile.Path
This works fine. But if i move the spreadsheet which has the hyperlinks in it to another folder, all the hyperlinks change relative to the folder where I move the spreadsheet to.
Is there a way to stop this happening and fixing the hyperlinks path.
Thanks

Try adding the hyperlink full path formula rather than the hyperlink object
Sub AddHyperlinkFormula()
Dim strMyPath As String, strMyFile As String, strName As String
strMyPath = "C:\Path\to\"
strMyFile = "Workbook.xlsx!"
strName= "Alt Text!"
ActiveCell.Formula = "=HYPERLINK(""" & strMyPath & strMyFile & """,""" & strName& """)"
End Sub

The same thing drove me nuts.. '=hyperlink' is not always a choice since it has a 255 maxchar limitation. So the best solution is indeed to set the hyperlink base (which is workbook-specific). Can be done in two ways:
1) File -> Properties -> Summary Tab -> Hyperlink base
2) or with vba ActiveWorkbook.BuiltinDocumentProperties(29)

Related

Excel 2016 Macro to edit Hyperlink

Currently I need to change over hundreds of cells of hyperlinks to a new format that is being used.
Previously we would have for example "https://oldServer:oldPort/project_code/Some_File"
and we are now moving to
"https://newServer:newPort/project_code/Some_File".
I only want to be able to change the "oldServer:oldPort" to "newServer:newPort" without changing the rest of the hyperlink.
I know an excel macro would be the easiest solution but I do not have the experience to be able to create one.
You'd want to loop through each of the hyperlink objects in each sheet.
Code something like this should work. (Make sure you backup before testing this, since I can't test on your actual data!)
Also, note that this changes the link but not the text displayed, since I'm not sure what that consists of. The text could be changed with the same procedure by updating TextToDisplay, or else by using Find & Replace.
Edit: (added confirmation on each change.)
Sub changeLinks()
Const oldPrefix = "https://oldServer:oldPort/"
Const newPrefix = "https://newServer:newPort/"
Dim h As Hyperlink, oldLink As String, newLink As String
For Each h In ActiveSheet.Hyperlinks
'this will change Address but not TextToDisplay
oldLink = h.Address
Debug.Print "Found link: " & oldLink
If Left(oldLink, Len(oldPrefix)) = oldPrefix Then
newLink = newPrefix & Right(h.Address, Len(h.Address) - Len(oldPrefix))
If MsgBox("Click OK to change:" & vbLf & vbLf & oldLink & _
vbLf & vbLf & "to" & vbLf & vbLf & newLink, vbOKCancel, _
"Confirmation?") <> vbOK Then Exit Sub
h.Address = newLink
Debug.Print " Changed to " & h.Address
End If
Next h
End Sub
I removed the hyperlink from the column containing the old server information. Then I created a couple of new columns. I typed in the full path to the new server in the first new columns and filled it down. In the other new column I created a formula to concatenate the full path and the friendly name (which happened to be what the link was originally named). This created the new server path along with the file name. I copied/pasted values of this column and deleted the contents of the first new column I created. I then used the HYPERLINK formula to put the hyperlink and the friendly name back together. It sounds more convoluted than it was - took me longer to write it down here than to actually do it in my Excel spreadsheet. I hope this makes sense.

Titles in one CSV, Hyperlinks in other CSV, create new CSV with links built in

I have plain text titles in one .csv and hyperlinks for those titles in another .csv
I currently open them in the same work book, put the titles in A, the hyperlinks in H, and use
=HYPERLINK(H1,A1)
to get my final output of Titles with hyperlinks built in.
Is there an easy way (Excel VBA or macro) to bypass the manual work and create a new output file with the "Titles with hyperlinks built in" from the original two .csv files?
Edit: My two .csv files have the respective text (hyperlink and titles) all down column A.
Sub buildlinks()
Dim i As Integer
Dim wb1, wb2 As Workbook
Set wb1 = Application.Workbooks.Open("C:/path/Links.csv")
Set wb2 = Application.Workbooks.Open("C:/path/Titles.csv")
i = 1
Do Until wb1.Sheets("Sheet1Name").Cells(i, 1).Value = ""
ThisWorkbook.Sheets("Sheet1Name").Cells(i, 1).Formula = "=HYPERLINK(" & wb1.Sheets("Sheet1Name").Cells(i, 1).Value & "," & wb2.Sheets("Sheet1Name").Cells(i, 1).Value & ")"
i = i + 1
Loop
End Sub
Assuming you want to create the hyperlinks in the current spreadsheet instead of creating a separate file.
Since you've said that the inputs are really just text files, one item per line, not comma-separated, it's actually pretty simple to implement using the VBA file handling commands.
Sub BuildLinks(titlesFilePath as String, linksFilePath As String, ByVal rowStart As Long)
Dim tf As Long, lf As Long, of As Long
tf = FreeFile
On Error Goto NO_TITLE_FILE
Open titlesFilePath For Input As #tf
lf = FreeFile
On Error Goto NO_LINKS_FILE
Open linksFilePath For Input As #lf
On Error Goto 0
While Not (EOF(tf) Or EOF(lf))
Dim curTitle As String, curLink As String
Line Input #tf, curTitle
Line Input #lf, curLink
Cells(rowStart, 1).Formula = "=HYPERLINK(""" & curLink & """,""" & curTitle & """)"
Wend
Close #tf
Close #lf
Exit Sub
NO_TITLE_FILE:
MsgBox "Can't Open Title File" & titlesFilePath
Exit Sub
NO_LINKS_FILE:
MsgBox "Can't Open Links File" & linksFilePath
End Sub

Excel VBA - disable form before saving

I have created a simple spreadsheet in Excel 2010 containing a form that loads as the spreadsheet opens. The employee fills out the required form data and presses a "Save" button macro utilizing the SaveAs method.
My question is if it possible to disable the form in the saved copy? The reason is that I would like to avoid the form to load when our bookkeeping department opens the copy to review the data.
To clarify this is how my vba code is
Sub SaveAsButton()
Dim applicationUserName As String
Dim saveLocation As String
Dim fileName As String
Dim weekNo As String
Dim year As String
weekNo = ThisWorkbook.Sheets("Service").Range("M4").Value
Debug.Print (weekNo)
year = ThisWorkbook.Sheets("Service").Range("R4").Value
Debug.Print (year)
applicationUserName = Application.UserName
Debug.Print (applicationUserName)
saveLocation = "w:\Service Users\" & applicationUserName & "\Service\"
Debug.Print (saveLocation)
fileName = "Service" & "-" & weekNo & "-" & year & "-" & applicationUserName
Debug.Print (fileName)
fileName = Replace(fileName, " ", "")
Debug.Print (fileName)
ThisWorkbook.SaveAs (saveLocation & fileName)
End Sub
Thank you.
If you don't need any code in the final workbook you could simply save as .xlsx and thereby remove all the vb components
You may want to use CustomProperties for that.
First, create a CustomProperty:
ActiveWorkbook.CustomDocumentProperties.Add "Saved", False, msoPropertyTypeNumber, 0
Change the value of the CustomProperty to 1 when user saves the form (add the following code to SaveAsButton()):
ActiveWorkbook.CustomDocumentProperties("Saved").Value = 1
Add a check if ActiveWorkbook.CustomDocumentProperties("Saved").Value = 0 to the method which opens the form.

Automatically name a file based on cell data when saving a spreadsheet?

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).

Display text link to open specific PDF page from Excel

I found a VBA code online that opens up an internal (shared drive) PDF document page in IE (e.g. goes to page 8 of PDF file). I would like to display text in the cell for a user to click (e.g. "Click here to view").
Problem: The cell currently displays '0' and I have to go to the function bar and hit [Enter] to execute.
Excel Version: 2003
Function call:
=GoToPDFpage("S:\...x_2011.pdf",8)
VBA Code:
Function GoToPDFpage(Fname As String, pg As Integer)
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Navigate Fname & "#page=" & pg
.Visible = True
End With
End Function
:EDIT:
I was able to display text, but it's still not a link like I wanted.
="Click to view" & GoToPDFpage("S:\...x_2011.pdf",8)
Thank you for your help.
If you dont have a high complex workbook/worksheet you could try the following:
Turn the "Click to view" cell into a Hyperlink with following characteristics.
Make it point to itself
The text inside the cell must always be the string Page= plus the number that you what the pdf to open in. Eg.: Page=8
Then go to the workseet module and paste the following code:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Left(ActiveCell.Value, 4) = "Page" Then
GoToPDFpage Range("A1").Value, Mid(ActiveCell.Value, 6)
'This code asumes that the file address is writen in the cell A1
End If
'
End Sub
'
The above written code will trigger every time you run a hyperlink in the worksheet.
As the hyperlink always point to itself, the "Activecell.Value" will always have the page number that you want to open.
I'm assuming that you can put the file address in the cell A1. You could modify this portion to point to any other cell. (including: The cell to the right of the current hyperlink, etc).
This might not be the best option, but if you only need a quick feature in a couple of cells, it might be enough.
Hope it helps !
EDIT:
To make each HLink reference to itself, you can select all the cells where you have the links and then run this procedure:
Sub RefHLink()
Dim xCell As Range
For Each xCell In Selection
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:="", SubAddress:= _
xCell.Address, ScreenTip:="Click Here", TextToDisplay:="Page="
Next xCell
End Sub
how about letting excel write a batch file then running it?
*edit paths to pdf and AcroRd32.exe
Sub batfile()
Dim retVal
filePath = "path\pdf.bat"
pg = 2
Open filePath For Output As #1
Print #1, "Start /Max /w " & Chr(34) & "Current E-book" & Chr(34) & " " & Chr(34) & "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" & Chr(34) & " /a " & Chr(34) & "page=" & pg & Chr(34) & " " & Chr(34) & "H:\Documents\RPG\Dragonlance\New folder\Sample File.pdf" & Chr(34) & ""
Close #1
retVal = Shell(strFilePath)
End Sub
Try Menu->Data->Data Validation. In the 2nd tab you can write your message.

Resources