How to pass the hyperlink string from one workbook to another - vba

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.

Related

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.

Execute macro when clicked on hyperlink

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

VBA: Populating ListBox ActiveX control, on worksheet and not user form

I'm trying to populate a List Box (ActiveX control). This list box is on a sheet labeled "Dashboard" of my workbook, and not a user form. I want to populate it with a range from a sheet labeled "Data".
My problem is that if I populate it on the workbook open event procedure, I get an error when the workbook opens that it "Can't execute in break mode." However, there aren't breakpoints active at all.
If I populate it on the "Dashboard" worksheet active event procedure, it won't populate when the workbook is open. It only populates if I click on another worksheet, and then go back to the Dashboard worksheet, then it will populate.
Is there a better way to populate the list box so that it's always populated and ready to go? I have a lot of vLookup functions that are associated with the list box, and if the list box is not populated, then the rest of my code won't work.
I will post my codes that I have so far. The first is when I attempt to populate the listbox through the workbook_open even procedure. The second is through the "Dashboard" worksheet activate procedure.
Private Sub Workbook_Open()
Dim strName As String
Dim blDone As Boolean
Dim cPlanets As MSForms.ListBox
Dim vArray As Variant
Dim shtData As Worksheet
Dim wkbSolarSystem As Workbook
Set wkbSolarSystem = Application.Workbooks("workbookname.xlsm")
Set shtData = wkbSolarSystem.Worksheets("Data")
Set cPlanets = wkbSolarSystem.Worksheets("Dashboard").lstPlanets
vArray = shtData.Range("Planets").value
cPlanets.List = vArray
cPlanets.ListIndex = 3
'input box message for user when workbook opens up
strName = InputBox("Hello! Please enter your name", "Welcome!")
'check if there is a name entered via loop and if statement
Do
If Len(strName) = 0 Then
'if no name entered, ask user again
MsgBox ("Please enter a valid name to continue"), vbCritical, "Valid Name Required"
'ask user to type in name again
strName = InputBox("Hello! Please enter your name", "Welcome!")
Else
'display message with information for user
MsgBox ("Hello, " & strName)
blDone = True
End If
'finish loop statement
Loop Until blDone = True
This next code is the one I have on Sheet3 code worksheet activate procedure
Private Sub Worksheet_Activate()
Dim shtData As Worksheet
Dim wkbSolarSystem As Workbook
Set wkbSolarSystem = Application.Workbooks("workbookname.xlsm")
Set shtData = wkbSolarSystem.Worksheets("Data")
lstPlanets.List = shtData.Range("Planets").value
lstPlanets.ListIndex = 3
End Sub
You are declaring cPlanets as MSForms.ListBox, but in your question you say you are working with an ActiveX listbox on a sheet. So you should declare cPlanets as an Object, like:
Dim cPlanets As Object
Set cPlanets = wkbSolarSystem.Worksheets("Dashboard").lstPlanets
I tried this code on a different computer, and it works. It seems that it's the computer configuration that was causing the issue. The code works fine as it should on several different computers.

Input Box on workbook open

I am trying to come up with some vba code to open an input box automatically as soon as the workbook is opened and have the user enter a date and then have the date placed in the A1 cell. I have written the code below but the input box is not pulling up at all it just opens the workbook and moves on.. not sure what is happening. Any and all help is appreciated.
Thanks!
Option Explicit
Private Sub workbook_open()
Dim cellvalue As Variant
Dim ws As Worksheet
Set ws = Worksheets("Workbench Report")
ReShowInputBox: cellvalue = Application.InputBox("Please Enter Todays Date (dd/mm/yyyy)")
If cellvalue = False Then Exit Sub
If IsDate(cellvalue) And CDate(cellvalue) < Date Then
ws.Range("A1").Value = DateValue(cellvalue)
Else: MsgBox ("Invalid Date!")
GoTo ReShowInputBox
End If
End Sub
Your code triggers upon the Workbook opening for me. Try these steps.
Open up Excel and Save As, changing the extension to .XSLM
Open up the VBA Editor (ALT + F11)
In the left-hand window, locate your macro file (the one you just created and named - it's in brackets after "VBA Project"), drilldown to "This Workbook" and double-click it.
Paste your code into the right-hand window
Save the file and re-open.
See attached diagram.
By the way, "cellValue = false" should probably be cellValue = "" since InputBox is returning a string and not a boolean value.
For Workbook_Open events the script needs to reside in the private module (ThisWorkbook)
From Ozgrid:
the Workbook_Open event is a procedure of the Workbook Object and as
such, the Workbook_Open procedure MUST reside in the private module of
the Workbook Object (ThisWorkbook).

How to change RefersTo for named range?

I have a class ValidationChanger, with a method changeNamedRangeAddress that should change the RefersTo address for a named range. However, my code is unexpectedly wrapping the new address in double quotes.
Class definition for ValidationChanger here:
'ValidationChanger
Sub changeNamedRangeAddress(bk As Workbook, rangeName As String, newAddress As String)
bk.Names(rangeName).RefersTo = newAddress
End Sub
I test it on a range named TestRange, which refers to an address in sheet Instructions: Instructions!$A$133:$A$138. My test should change the address to Instructions!$A$133:$A$139 with the following:
Sub testValidationChanger()
Dim vc As New ValidationChanger
Dim bk As Workbook
Set bk = Workbooks("test.xlsm")
Debug.Print bk.Names("TestRange").RefersTo
vc.changeNamedRangeAddress bk, "TestRange", "Instructions!$A$133:$A$139"
Debug.Print bk.Names("TestRange").RefersTo
End Sub
The output is:
=Instructions!$A$133:$A$138
="Instructions!$A$133:$A$139"
Any idea why the new address is wrapped in double quotes (which makes it function as a text string instead of an address)?
Pass the new range as a range object, and not as a string:
vc.changeNamedRangeAddress bk, "TestRange",[Instructions!$A$133:$A$139]
The reason you got a text string is that you did not preface the text string with an = sign (so that Excel would know it was supposed to be a formula)
If you use a named range instead of the addresses then you can alter that named range to adapt to whatever you want.
'this line creates the name that you can use in formulas in
'much the same way as "Instructions!$A$133:$A$139"
thisworkbook.Names.Add Name:="examplerange", RefersTo:=Range("A1:A5")
'this line changes what it's pointing to
thisworkbook.Names("exampleRange").RefersTo = Range("A1:A10")