Running a VBA function by clicking an Excel cell - excel

When a specific cell is clicked, I need to run a function. The function is:
HighlightOnWebsite(url As String, phrase As String)
Basically, this function loads a Web Browser Control, brings up the requested page, and highlights the required phrases. The function works more ore less fine.
What I can't figure out is how to get certain cells to call this function.
Lets say each row has 3 cells which contain the following information:
url of some document | some important phrase | will contain call to function
Now, I need to scan the spreadsheet and in the third column of each row, make a clickable cell which calls a function like HighlightOnWebsite(A1,A2).
Would something like this be possible?

You don't have to scan the worksheet.
Create, in each cell of the third column, a static hyperlink that links to that same cell.
Then have a handler in the worksheet:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.Range.Column = 3 Then
HighlightOnWebsite Target.Range.Offset(0, -2).Value, Target.Range.Offset(0, -1).Value
End If
End Sub

Related

How do I run an Excel macro using values from different rows in a table?

I am writing an Excel macro to send emails from data in a spreadsheet. The data are in a table with each column providing different variables to create the email (to:, cc:, subject, attachments, etc).
I've got the macro to do what I want on one line of the table. My question is:
How do I scale the VBA code to work for each line of my table? I would like a hyperlink in each row to run the macro using the data in that row. Below is a small snippet of my code as an example:
Sub SendMail()
Dim xContractNumber As String
xContractNumber = Worksheets("Program Info").Range("L10").Value
End Sub
In the above example, I would like a hyperlink that runs the macro using the data in row 10 of the 'Program Info' sheet... And another button or link that would run the macro using data in row 11, and so on.
This answer attempts to combine many of the good answers and comments everyone has already given. The code below contains the functionality for both buttons and hyperlinks in a condensed way.
This code could go in one separate module:
Sub SendMailByButton()
SendMailForRow ActiveSheet.Buttons(Application.Caller).TopLeftCell.Row
End Sub
Sub SendMailForRow(ByVal r As Long)
If r < 1 Then Exit Sub 'Failsafe in case the row number is invalid
Dim xContractNumber As String, xValueInColumnM As String, xValueInColumnN As String
xContractNumber = ActiveSheet.Cells(r, 12).Value 'Col 12 is col "L"
xValueInColumnM = ActiveSheet.Cells(r, 13).Value
xValueInColumnN = ActiveSheet.Cells(r, 14).Value
'...etc.
'...Rest of code to send the actual email
End Sub
If buttons are used, SendMailByButton must be attached to every button's click event, and the above code would be enough.
If manually-added hyperlinks are used, the above code would need to be complemented with the following code in the sheet module for every sheet that uses the hyperlinks (in your case, you may only need to add this code in one sheet's module) ...
'This event is fired when the hyperlink is clicked
Private Sub Worksheet_FollowHyperlink(ByVal target As Hyperlink)
On Error Resume Next
SendMailForRow target.Range.Row
End Sub
Each manual hyperlink would have to link to the same cell it is sitting on (i.e. to a "Place in This Document" with the cell reference set to its current cell).
The problem remains that you will need to manually create a button or hyperlink for every row in your table, which can be a hassle, especially if there are many rows or if the number of rows can grow in future.
A way to circumvent this problem is to have an extra button at the top of the table that allows the user to automatically create the buttons and/or hyperlinks for each row of data (removing excess buttons or hyperlinks if the table shrinks in size). This may require that you post a separate question.
Another way to circumvent this problem is to forego buttons altogether and, instead, use Excel formulas with the native HYPERLINK function (replacing the "regular" links). In that case, the FollowHyperlink event handler above would no longer be needed, but you would need to add the following function (which can go in the same module where SendMailForRow would reside) ...
Function SendMailByHLink()
SendMailForRow ActiveCell.Row
Set SendMailByHLink = ActiveCell
End Function
You would then have to create an Excel formula such as the following in each row (in the column where you want the hyperlink) ...
=HYPERLINK("#SendMailByHLink()", "Send email")
Entering this formula will auto-generate a hyperlink in the cell, and it will tell Excel to execute function SendMailByHLink when the hyperlink is clicked. The function after the "#" is supposed to return the link's target, which is why SendMailByHLink returns ActiveCell to ensure that the focus remains on that cell (if you prefer, you could return another cell such as ActiveCell.Offset(, -2) so that the user is taken to the cell 2 columns back in the same row after the link is clicked). Before returning ActiveCell to Excel, SendMailByHLink will execute the email-sending code.
The nice thing about using a HYPERLINK formula is that you can easily copy/paste the formula up and down the all the rows in the table. Therefore, if your table increases in size, all the user has to do is to copy/paste the HYPERLINK formula into the new rows. The user can also delete excess HYPERLINK formulas if the table shrinks. It may even be possible to have Excel automatically copy the formula if the data is sitting on an official Excel table by using a calculated column.
Sorry for all the extra explanation. If you focus on the code blocks, you will see that the solution is simpler than it looks.

Need to run a macro based on unique ID in worksheet cell

Users will enter new information into a sheet using an userform. This information is tied to a unique ID given at time of entry (i.e. 2019-7 for the 7th item in this year). Currently, each piece of information is placed into separate cells in a row. I want to hide some of these cells but be able to allow users to click on the unique ID at the start of that row, which will run a macro that will create a new sheet to display all information in a user friendly way.
I have tried creating a hyperlink to a run a macro but the code for identifying the hyperlink can't be cell specific. I need a more dynamic way to have excel recognize which ID was clicked and then use that to gather the rest of the information in that row (i.e. the hidden columns).
My best option had been to put a private sub in the worksheet to recognize when a cell was changed/clicked but couldn't get past it just identifying the cell. I need it to then identify the contents of that cell, which would be the unique ID.
I have no issues with creating a hyperlink to nothing, I just need excel to run a macro when a hyperlink is clicked and then within that macro, identify the unique ID and/or row that was clicked. Once I have the ID or Row identified, I then can go from there to grab the rest of the info in the other columns.
You can use the BeforeDoubleClick event of the Worksheet:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Address <> "$A$7" Then Exit Sub
' below, call the functions/subs that produce your output worksheet
MsgBox "You clicked on " & Target.Address
End Sub
Above only works on cell A7. If you need this to apply to entire column A, modify slightly:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
' below, call the functions/subs that produce your output worksheet
MsgBox "You clicked on " & Target.Address
End Sub

Excel VBA : Hyperlink that fills target cell's contents with hyperlinked text

There are a lot of similar questions on here about VBA and hyperlink in excel, but nothing that I could modify to my own situation.
On one sheet I have a column of names (E:E), and on another I have a cell (D13).
What I want to do is hyperlink each cell in column (E:E) such that, when clicked, the hyperlink not only takes me to cell (D13) but also populates cell (D13) with the name that I clicked on.
So, click "John Smith" (Sheet1!E1) ---> (Sheet2!D13) = "John Smith"
First you need a tiny piece of code in a standard module to install the hyperlink in Sheet1:
Sub MakeLink()
Sheets("Sheet1").Hyperlinks.Add Anchor:=Range("E1"), Address:="", SubAddress:="Sheet2!D13", TextToDisplay:="Stuff"
End Sub
Then you need an event macro in the worksheet code area to do the content transfer:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
ActiveCell.Value = Sheets("Sheet1").Range(Target.Parent.Address).Value
End Sub
I think the best solution may be to use VBA. If you're unsure on how to do that, record s macro that selects a cell in e, then goes to D13 and updates its value, then look at the code that was recorded and use those snippets to create your code. At a high level you'd want to trigger a macro on click of any cell in column E that does something like:
Dim e_value = <value of selected cell in column E>
ThisWorkbook.Sheets("name of sheet 2").Range("D13") = e.value
Application.Goto Reference:=Worksheets("Sheet2").Range("D13"), Scroll:=False
Note that the above contains pseudocode, but it should give you a general idea on how you could proceed.

Excel: Hyperlink to a cell specified by another cell's value

I have a document that needs to generate a hyperlink to a cell in the same workbook by getting the address from another cell. Here's what I have right now:
=hyperlink(CELL("address",INDEX('Budget Record'!C3:C105,MATCH(Y73,'Budget Record'!C3:C105,0),1)))
This displays the appropriate location:
'[Calendar Budget.xlsx]Budget Record'!$C$3
However, when clicked, it says that Excel cannot open the specified file.
I have tried manually creating a hyperlink to that value, and it still doesn't appear to work:
=hyperlink('[Calendar Budget.xlsx]Budget Record'!$C$3)
However, if I plug that into the goto dialogue box, it has no problems with it.
Am I missing an extra step?
After looking into all of the built-in hyperlink options that Excel offers, I could not find a way to have Excel link you to a dynamic/ changing cell reference. Naturally, I turned to VBA :)... this is a very simple macro with only a few lines of code. Give it try:
Press Alt + 11 to open the Visual Basic Editor (VBE)
If your project explorer is not already open, click this icon:
Double click the worksheet tab that you want the hyperlink to work on:
Paste the following code into the white space:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'check if user is selecting the 'hyperlink' cell
If Target.Address = "$A$1" Then
'run the 'selectCell()' subroutine
Call selectCell
End If
End Sub
Sub selectCell()
Dim goToAddress As String
'get cell address
goToAddress = Range("A2").Value
'send user to this cell
Range(goToAddress).Select
End Sub
Go to your worksheet and test the script by typing G3 in cell B1.
Select cell A1. The macro should have automatically selected cell G3.
Hope this helps!
(Posted on behalf of the OP).
I have identified a solution. Basically it looks like the problem was in the formatting.
Basically I needed three steps. The first one is getting the location of the cell returned as a full address (including the file, sheet, and Cell). I do that with this:
=CELL("address",INDEX('Budget Record'!C3:C105,MATCH(Y73,'Budget Record'!C3:C105,0),1))
Here's a sample of what that results in:
'[Calendar Budget.xlsx]Budget Record'!$C$3
The problem with this is that the apostrophe at the beginning is in the wrong spot. To work as a hyperlink, the string should be this:
[Calendar Budget.xlsx]'Budget Record'!$C$3
So, I have a step where I remove the first 22 characters of the starting string:
=RIGHT(Z73,LEN(Z73)-23)
This results in the following:
Budget Record'!$C$3
Next, I need to add on this to the start of the string:
[Calendar Budget.xlsx]'
I do that with the following:
=HYPERLINK("[Calendar Budget.xlsx]'"&AA73)
The resulting output looks like this:
[Calendar Budget.xlsx]'Budget Record'!$C$3
So, we have a hyperlink to a cell in another sheet that dynamically changes depending on the initial referenced cell.

Excel: retrieve hyperlink from an image in a cell

In an Excel sheet (created by importing external data and images) are several cells that each contain different image and that image has a hyperlink. These cells containing images are all in one column.
How can I retrieve that hyperlink from each image?
The hyperlink is NOT retrievable from that cell.
I've got a user-defined function that easily retrieves hyperlinks from any cell (if there is a hyperlink).
Function GetURL(rng As Range) As String
On Error Resume Next
GetURL = rng.Hyperlinks(1).Address
End Function
This function can be placed anywhere.
For example: In cell c25 the URL from a hyperlink in cell A1 must be listed.
For that simply enter the following formula in cell c25.
=GetURL(A1)
That works just fine.
However, if that cell A1 contains an image with a hyperlink, then the result is nil (or nothing). Even though the hyperlink is there as part of that image.
Apparently the image is an object that needs to be addressed.
How can this be done?
Just found a possible duplicate. Unfortunately the answer didn't get me any further.
Please add sample code.
Thanks.
A shape also has a Hyperlink.Address
A shape is defined on a sheet, and also has a name.
Putting these together, I came up with the following function:
Function PicURL(Pic As String, Optional SheetName As String) As String
If SheetName = "" Then SheetName = Application.Caller.Worksheet.Name
On Error Resume Next
PicURL = Sheets(SheetName).Shapes(Pic).Hyperlink.Address
End Function
Use:
If picture is on the same sheet, then =PicURL("Picture 1") will return the target address.
If the picture is on another sheet, then =PicURL("Picture 1","Sheet1") would be needed.
If the picture is in a different worksheet, then that's a whole different ballgame, and I leave that as an exercise for the reader.

Resources