Excel 2016 Macro to edit Hyperlink - excel

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.

Related

Show a commandbutton on datapulled lines

Once every 3 months we make a file available for our engineers.
This Excel files, pulls data from an Access file and shows it in Excel format.
Since some of this data doesn't change, we don't know whether the engineers haven't looked at it or whether the value isn't changed. What i'm trying to implement is some sort of "confirmation" button so we know the value shown is actually confirmed.
What i'm trying to do is enter an extra column in our access file called "confirmation".
When we pull this data in our excel file, i'm trying to find a way to convert that "confirmation field" into a commandbutton so whenever the data gets pulled, a commandbutton shows up on every line. Whenever the button gets clicked, the data gets saved in our Access file so we know the line is actually confirmed.
Maybe there are some other , easier, ways to do this?
I currently have some code to save excel data in Access but its not working in its current form:
Sub S_SaveDataToDB()
If ActiveSheet.Name = "Estimate" Then
ViKey = 1
Else
ViKey = 2
End If
For i = 1 To ActiveSheet.ListObjects("TB_ACC" & ViKey).ListRows.Count
VsData = "SET [BE] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 17)) & "', [PO STATUS] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 18)) & "', [REMARKS] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 19)) & "', [LOGDATE] = '" & Now() & "', [LOGID] = '" & Environ("Username") & "' WHERE [PO item] = '" & ActiveSheet.Cells(7 + i, 9) & "'"
If Len(F_FilterData(ActiveSheet.Cells(7 + i, 16))) + Len(F_FilterData(ActiveSheet.Cells(7 + i, 17))) + Len(F_FilterData(ActiveSheet.Cells(7 + i, 18))) > 0 Then Call S_UpdateDataInDB(VsData)
Next i
MsgBox "Data has been saved"
and
Sub S_UpdateDataInDB(VsData)
Dim cnDB As New ADODB.Connection
VsDBPath = ThisWorkbook.Sheets("Settings").Range("B2").Value
VsTable = "KCD"
cnDB.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & VsDBPath & ";" & "Jet OLEDB:Engine Type=5;" & "Persist Security Info=False;"
cnDB.Execute ("UPDATE " & VsTable & " " & VsData)
cnDB.Close
End Sub
Differences here are:
I want to just save text ("Data confirmed") for that particular cell.
So if one wants to confirm data on Row 8 and clicks "Data confirm". It should only save "Data confirm" for row 8 in access.
Generally, when I'm trying to add a feature to every row in a column, I'll use a hyperlink. It fits neatly into the cell, it can be anchored to a specific cell, and it also shows when it's been followed (the color changes). I've mocked together some code as an example; try to adapt it to your application and let me know if you need help.
First, in a standard module, enter the following code to create the hyperlinks. Presumably, you'd embed this into the code that pulls the data.
Sub PullData()
Dim sh As Worksheet
Dim lastRow As Long
'Pull the data
' DO STUFF
'Identify the range of the pulled data
Set sh = Sheets("PulledData")
lastRow = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
'Loop from row 2 through last row
For i = 2 To lastRow
'Assuming the 'save' option is in Column c
sh.Cells(i, "C").Hyperlinks.Add Anchor:=sh.Cells(i, "C"), Address:="", _
SubAddress:="", TextToDisplay:="Click To Save"
Next i
End Sub
Next, in the worksheet code for the sheet with the data, enter the below code. This tells the application what to do when a hyperlink is clicked. I created a fake function that is meant to mimic saving the data. You can change this as needed, or use a different design if it suits your needs better.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
'Confirm that this is a hyperlink in column 3
If Not Intersect(Target.Range, Columns(3)) Is Nothing Then
MsgBox SaveData(Target.Range)
End If
End Sub
Private Function SaveData(rng As Range) As Boolean
Debug.Print rng.Address & " has been saved."
SaveData = True
End Function

Multiple variables from a single user input

I'm writing some VBA code that should go through all Excel files in a specific folder (folder names always formatted with Month Year, e.g. May 2020). In my code I also need to use the individual "Month" and "Year" strings e.g. "May" and "2020", and the date format mm/??/yy e.g. 5/??/20 (the day doesn't matter, so I just put ? as a placeholder) which are stored as variables.
So far, I am using Application.FileDialog(msoFileDialogFolderPicker) to let the user choose the folder, and I'm using InputBox("") three times to get the strings and date.
Is there a way to condense this so that the user only has to do one to two things, instead of four?
According to this answer combo box in a date format it seems like a combo box could work (maybe getting the month and year inputs as strings and getting the folder and date based on that?), but is there a better a way?
Any help would be appreciated!
This is the way it might work.
Ask the user for a date
From the date the macro creates the folder name
The path of the folder is stored in the macro
The code below implements and supports that work flow.
Sub GetFolderName()
Dim Inp As String
Dim FolderName As String
Dim FilePath As String
' make sure you ask for a date format that your computer can recognise
' it depends upon your Regional Settings (in Windows Control Panel)
Do
Inp = InputBox("Enter a date", "Date format dd/mm/yy", _
Format(Date, "dd/mm/yy"))
If Inp = "" Then Exit Sub ' blank or Cancel
If Not IsDate(Inp) Then
MsgBox "Sorry, I can't recognise your entry" & vbCr & _
"as a date. Please observe the date" & vbCr & _
"format requirement and try again."
End If
Loop While Not IsDate(Inp)
FilePath = Environ("userprofile") & "\Desktop\"
FolderName = Format(CDate(Inp), "mmmm yyyy")
MsgBox "Folder name is """ & FolderName & """" & vbCr & _
"File path = " & FilePath
' complete path is
Debug.Print FilePath & FolderName
End Sub
Note that the following options were not utilized but are still available.
Day(Cdate(Inp)) ' returns the day of the entered date
Month(Cdate(Inp)) ' returns the number of the month of the entered date
Year(Cdate(Inp)) ' returns the year of the entered date (45-digit)

How can I prevent a custom excel hyperlink from triggering with either dragging the fill handle--I only want it to respond with a click

Ok so I have a hyperlink function in a spread sheet cell of the form:
=HYPERLINK(JJmp(I1030), I1030)
With the function JJmp():
Function JJmp(x) As String
dim iint as variant
iint = x
If IsNull(iint) Then GoTo out:
If Left(iint, 1) <> "_" Then GoTo out:
pat1 = """C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\Acrobat.exe"""
'pat1 = """C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe""" (this is the default, and I don't want to change the reg).
pat3 = "D:\__Numerical_Files_by_Page\" & iint & ".pdf"
pat3 = """" & pat3 & """"
Shell pat1 & " " & pat3, vbNormalFocus
JJmp = x
out:
End Function
For whatever reason the hyperlink based on this function has some very odd behavior. As stated in the title dragging the fill handle doesn't just fill the cells but also opens adobe for each one. Secondly, the hyperlink is super sensitive, I don't have to even click on it--just hovering over it will trigger acrobat 10 to open.
In essence its a very unstable hyperlink in that it is nearly self triggering. If I use the function directly I get an entry that requires some return key gymnastics to open acrobat.
I would just like this to respond like a normal hyperlink. TIA
This behaviour is because everytime you hover over the link or you drag it to a new field, excel tries to resolve the link before you click it meaning it executes your function. How else would it be possible for excel to keep your link up to date and provide it before you click it?
-> Your Function is not executed at the time to click at it as excel thinks, your function returns a link, which it then can follow.
You could try something like this:
herber hype2macro.
then don't use Shell in your UDF. What you want is more like this
Function JJmp(x) As String
If Not IsNull(x) And x Like "_*" Then _
JJmp = """C:\Program Files (x86)\Adobe\Acrobat 10.0\Acrobat\Acrobat.exe"" " & _
"""D:\__Numerical_Files_by_Page\" & x & ".pdf"""
End Function

Excel Hyperlinks change when I move spreadsheet

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)

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