Execute macro when clicked on hyperlink - vba

I have a worksheet where each row of the data table has a formula based hyperlink. I want those hyperlinks to execute a macro every time one of those is clicked. The macro needs to a parameter to act differently depending on which row's hyperlink is clicked, so for that I am using active cell's row number.
I have tried various ways I found but none of them complete the functionality. In most cases I need to specify the cell address in the event macro itself which is not a scalable option.
Sample Data:
Col A Col B
A Link: A
B Link: B
C Link: C
D Link: D
E Link: E
The second column in the above table should be a list of hyperlinks.
The hyperlink formula I am using in the second column (e.g. in cell B1):
=HYPERLINK(MID(CELL("filename"),FIND("[",CELL("filename")),FIND("]",CELL("filename"))-FIND("[",CELL("filename"))+1)&ADDRESS(ROW(),COLUMN()-1),"Link: "&$A1)
The macro I am using in the worksheet code:
Private Sub Workbook_SheetFollowHyperlink(ByVal Target As Hyperlink)
Dim sData As String
sData = "text: " & sData & Range(Target.Range.Address). _
Offset(0, -1).Value & vbCr
MsgBox sData
End Sub
For me in this case, the above macro is not even running when I click on the hyperlink

In Excel 2013 - the method 'signature' for the Workbook_SheetFollowHyperlink has an additional argument to your event handler. Can you include the ByVal Sh As Object in your code and try again:
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
'your code goes here
End Sub

Related

Clicking a hyperlink in Excel to set an auto filter on a different sheet

I have a detailed product order worksheet example table 2. and a summary worksheet supplier name and total value example Table 2.
I want to know is it possible when I click the hyperlink details will filter my detailed product order sheet under this supplier all order example table 3.
If anyone can do this for me it will be helpful for me
Table 1
Table 2
Table 3
You can use the Worksheet_FollowHyperlink event to detect when a hyperlink has been pressed. A hyperlink to a location within the document will have a SubAddress, and the text that you clicked on will be the TextToDisplay.
The following code will detect when you click a hyperlink to a worksheet and - if that worksheet has an autofilter - will filter the first column of the AutoFilter for the text that you clicked on.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim wsToFilter As Worksheet
On Error GoTo SubErr
If Right(Target.SubAddress, 3) = "!A1" Then 'Hyperlink is to a worksheet within this document
Set wsToFilter = ThisWorkbook.Worksheets(Replace(Target.SubAddress, "!A1", ""))
If wsToFilter.AutoFilterMode Then 'Hyperlink has an AutoFilter
wsToFilter.AutoFilter.ShowAllData 'Remove existing filters
wsToFilter.AutoFilter.Range.AutoFilter 1, Target.TextToDisplay 'Filter the First column for the text of the hyperlink
End If
Set wsToFilter = Nothing
End If
SubErr:
End Sub
Use the Worksheet.FollowHyperlink Event to filter the desired data.
Option Explicit
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox Cells(Target.Parent.Row, "A") 'returns the value of column A of the clicked link
'do your filter stuff here …
End Sub

Automatically change sheet names

The following code adds/deletes sheets and inserts a list of all the sheet names while making them hyperlinks:
https://stackoverflow.com/a/48159499/9102830
The following code changes the sheet name depending on several cell names:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Address(0, 0) = "C13" Then
Sh.Name = Sh.Range("B33").Value + "_" + Sh.Range("C13").Value + "_" + Sh.Range("C22").Value + "_N01"
End If
End Sub
The questions are:
Instead of changing when the cell input changes, can this be done automatically?
Could it be a part of the "Sub add_sheet" code? Like, if I add a sheet, it should be named depending on the cells, and since it is copied and the cells are the same, the name will obviously be taken, in which case the name should be "N02" instead of "N01" (instead of the default "(2)" that Excel does).
Finally, when/if the cells are changed, so that the sheet name is not equal to a previous sheet name, could it automatically go back to "N01"?
Thanks in advance!
There are a few ways you can handle that. One way is to combine Worksheet_Activate with Worksheet_Calculate, and throw in a public variable.
When you first open up your worksheet, you will automatically set the variable, and the variable will set with every change as well.
Option Explicit
Public myVar As Variant
Private Sub Worksheet_Activate()
'Set the public variable
myVar = Range("B33").Value
End Sub
Private Sub Worksheet_Calculate()
If myVar <> Range("B33").Value Then
sh.Name = ...
myVar = Range("B33")
End If
End Sub
You can also set the variable when you open the workbook with Workbook_Open as well. Really just depends on your particular needs.

How to pass the hyperlink string from one workbook to another

I have two workbooks "UI.xlsm" and "Gas_Insulated_MV_Circuit.xlsm", in the first workbook (UI.xlsm) i ave maintained a list of hyperlinks in a particular column, on click of the link it will take me to a respective other workbooks.
The task is to capture the text of the clicked hyperlink from "UI.xlsm" workbook and i have to use the same value in "Gas_Insulated_MV_Circuit.xlsm"
Below is the code from UI.xlsm workbook where I am capturing the clicked hyperlink cell text and storing it as string
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim BR as String
BR = Target.Range.Text 'Here i'm storing the clicked cell text
End Sub
Now i need to use the BR string value in another workbook "Gas_Insulated_MV_Circuit.xlsm"
Public BR as String ' I have declared BR as a public variable
Private Sub CommandButton27_Click()
Dim WbUI as Workbook
Dim WsUI as Worksheet
Dim File1 as string
Set WbUI = Workbooks ("UI.xlsm")
Set WsUI = WbUI.Sheets("Sheet1")
File1 = BR ' I want something like this, where i can assign BR value from
UI.xlsm workbook to File 1 of the current workbook
End Sub
Could anyone kindly help me in achieving it.
I created a defined name (e.g. myBR) in the UI.xlsm workbook with =Sheet1!A1 as the Refers to:. With that defined name 'seeded', I changed your Worksheet.FollowHyperlink event macro to,
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
ThisWorkbook.Names("myBR").RefersToR1C1 = _
Chr(61) & Chr(34) & Target.Range.Text & Chr(34)
End Sub
In the Gas_Insulated_MV_Circuit.xlsm workbook, I can retrieve the most recently clicked hyperlink's cell text (i.e. TextToDisplay property) with,
=UI.xlsm!myBR
With both workbooks open, the cell value changes were immediate. Assignment to a string or integer variable in VBA should be no problem.

running multiple macros when cells in a range are changed

bear with me, as I am a complete vba newbie and wrapping my head around what I already have has already taken me much longer than I care to admit.
I have a workbook with one master list "ITEMS" and several (up to 15) sub-tabs that grab information from the ITEMS sheet. I've been able to make this happen using buttons on each sub sheet which call this code:
Private Sub getNELL_Click()
Sheets("ITEMS").Range("A1:K400").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("ITEMS").Range("O1:O2"), CopyToRange:=Range("A1:K1") _
, Unique:=False
End Sub
This code successfully grabs each relevant row into the sheet each time I click the button, where each getX has a different name/criteria range (getRILEY, getELLE etc.)
But what I'm looking to do next is to have these macros run automatically when any cell in the G column of the ITEMS sheet is changed. In plain text, what I need is:
When [Any Cell in Column G] in Sheet("ITEMS") is changed
Run getNELL, getRiley, getELLE (x15 different macros)
here's my file with all the sheet (sic) in it.
EDIT:
and it's done!
moving the macros to a module instead of in each individual sheet, making them public and removing the _Click, along with the following code worked the magic I needed.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("G2:G400")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
getNELL
getMIKA
getRILEY
getJANNA
getWOO
getELLE
getMK
getLAURA
getFLIPSE
getJENN
getCRIS
End If
End Sub
First off, use this link as a resource for triggering an event when cells change. That's usually just in the subroutine declaration.
For the code, change all of your private subs to public subs by replacing "private" with "public". Then in your subroutine list the subroutines to call:
>
Subx
Suby
Subz
end sub
Sorry the answer isn't super detailed as I am typing from my phone. Also, those sub examples should each be on their own line. I can't seem to change that on here.
you have already created filter criteria in ITEM sheet (grey highlighted)
so create one mapping for what sheet needs what criteria range in INDEX sheet
e.g.
SheetName Criteria Mapping
nell O1:O2
mika P1:P2
riley Q1:Q2
janna R1:R2
woo S1:S2
elle O3:O4
mk P3:P4
laura Q3:Q4
flipse R3:R4
jenn S3:S4
cris O5:O6
Add this code in a Module
Public Sub pGet_Data(ByVal SheetName As Worksheet, ByVal CriteriaRng As Range)
ThisWorkbook.Worksheets("ITEMS").Range("A1:K400").AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=CriteriaRng, _
CopyToRange:=SheetName.Range("A1:K1"), _
Unique:=False
End Sub
And in Thisworkbook Module add given code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim rngCriteriaRange As Range
Dim rngOneMap As Range
Dim wksSheet As Worksheet
If Sh.Name = "ITEMS" And Target.Column = 7 Then
Set rngCriteriaRange = Sh.Range("W6:X16") '<--you can make it dynamic
For Each rngOneMap In rngCriteriaRange.Rows
Set wksSheet = ThisWorkbook.Worksheets(rngOneMap.Cells(1, 1).Value)
Application.StatusBar = "Updating [" & wksSheet & "] Sheet"
Call pGet_Data(wksSheet, wksSheet.Range(rngOneMap.Cells(1, 2).Value))
Next rngOneMap
End If
MsgBox "Sheets has been updated.", vbOKOnly, "Be Happy..."
ClearMemory:
Set rngCriteriaRange = Nothing
Set rngOneMap = Nothing
Set wksSheet = Nothing
End Sub
I think this will resolve what you are looking for... :)

Excel VBA - Capitalizing all selected cells in column on double click

I have a very simple VBA script, that capitalizes the selected cell:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
ActiveCell.Value = UCase(ActiveCell.Value)
End Sub
It works as expected, but sometimes I would like to capitalize all cells in a selected column, but only if I double click on the column itself. It seems that I cannot receive events with Worksheet_BeforeDoubleClick when clicking the column fields..
Is there some workaround for this?
Like I mentioned, Why not a shortcut key?. You can assign a shortcut key for your macro as shown below
Now all you have to do is select the column and press the shortcut key.
Also, instead of looping through every cell in a column, here is a code which is based on a ONE LINER HACK by Peter Albert.
Put this in a module.
Sub ChangeToUpper()
Dim rng As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
End If
Set rng = Selection
rng = WorksheetFunction.Transpose(Split(UCase(Join( _
WorksheetFunction.Transpose(rng), vbBack)), vbBack))
End Sub
Screenshot:
If DoubleClick is not mandatory, you could use BeforeRightClick. If you want to keep original right click context menu, you could import the module and check for Ctrl/Alt/Shift
Option Explicit
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim condition As Boolean
condition = True ' check Ctrl/Alt/Shift using http://www.cpearson.com/excel/KeyTest.aspx
If condition Then
MsgBox "Right Click at " & Target.Address
Cancel = True
End If
End Sub
Another option is to assign a Ctrl+[] in Macro options to a macro instead of an event handling and call the macro to process the Selection object.