How to change RefersTo for named range? - vba

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

Related

Set range via Range object -> Range object fails?

Can someone help me debug this piece of code?
....
Dim searchRng as Range
With Sheets("Database")
Set searchRng = Range("pointer.address:.cells(pointer.End(xlDown).Row,pointer.Column).address")
End with
I keep getting error 1004: Method 'Range' of object '_Global' failed
"pointer" is a previously defined range of one cell (B6).
After various debugging attempts, the problem seems to be connected to .address... Thats as far as I've been able to trace it back.
Thanks in advance!
Leo
The issue here is that the quotation marks are for when you are passing the name of a range to the .Range() object, but you are wanting to pass it the results of calling the .address method. If you put those method calls in quotation marks VBA wont run them and will instead try to interpret what you have in them as the name of the range you are referring to. You need to construct the range name string using these methods and pass the result to the .Range() object.
There are several ways you could do this. This first one separates out the construction of the range name and assigns that to a variable which can then be passed to .Range().
Sub test()
Dim searchRng As Range
Dim CllNameA As String
Dim CllNameB As String
Dim CllRange As String
With Sheets("Database")
CllNameA = .Range("pointer").Address
CllNameB = .Range("pointer").End(xlDown).Address
CllRange = CllNameA & ":" & CllNameB
Set searchRng = .Range(CllRange)
End With
End Sub
This next subroutine condenses the same methodology into one line. It's still doing the same thing, but as its doing it all at once its slightly more difficult for a human reader to follow.
Sub test2()
Dim searchRng As Range
With Sheets("Database")
Set searchRng = .Range(.Range("pointer").Address & ":" & .Range("pointer").End(xlDown).Address)
End With
End Sub
There are other ways of achieving the same goal, but I hope this at least sets you on the right path.

Call Subroutine from a string value VBA

trying to call this subroutine using a string. I have tried Application.Run like I have read online but that doesn't seem to be working.
The variable element will loop through and represents different state codes. So I have subs called "CA_Config", "GA_Config" "AZ_Config" etc.
Dim strSubToCall As String
strSubToCall = element & "_Config()"
Application.Run strSubToCall
State subs are very different therefore need to be different subroutines. The other subs and the main sub calling the other ones are all public.
Example for CA sub below
Public Sub CA_Config()
Dim rngLastHeader As Range
Dim intLastRow As Integer
Dim i As Integer
intLastRow = Sheet1.currWS.UsedRange.Rows.Count
Set rngLastHeader = Sheet1.currWS.Range("A1").End(xlToRight)
rngLastHeader.Offset(, 1).Value = "Use Tax Reversal Needed"
Sheet1.currWS.Range("X:X").EntireColumn.Copy
Sheet1.currWS.Range("Y:Y").PasteSpecial xlPasteFormats
Sheet1.currWS.Range("Y:Y").Columns.AutoFit
End Sub
Remove parenthesis and prepend your Sub name with module name. For instance, Application.Run "Module1.MySub".

how to convert formula into text?

I have cells(1,1)="=add(a,b)". I want modify this text and place it into some VBA variable string and NOT the result of calculation. In other words, I want to be able to see in some VBA variable the text = "=add(a,b)".
Use .Formula
Sub Foo()
Dim FormText as String
FormText = ActiveSheet.Cells(1,1).Formula
Debug.Print FormText
End Sub

Value in cell as variable in select formula

I have programmed the following VBA code:
Sub test()
Dim Variable As Variant
Variable = "R2:R11"
Sheet1.Select
Range(Variable).Select
End Sub
This formula works perfectly. Now I want to replace the "R2:R11" part of the variable and instead referring to a cell (W12) in the spreadsheet. In this cell I have written "R2:R11" and I changed the formula to the following:
Variable = Sheet1.Range("W12")
which leads to the following code:
Sub test()
Dim Variable As Variant
Variable = Sheet1.Range("W12")
Sheet1.Select
Range(Variable).Select
End Sub
However, with this formula I now get the ERROR 1004.
Do you guys have any solution how I can make the variable referring to the cell in the spreadsheet and then use it in the select formula?
Thanks for any help :-)
You need to declare your variables properly and access the actual .Value property of the Range object.
Sub test()
Dim Variable As String
Variable = Sheet1.Range("W12").Value
Sheet1.Select
Range(Variable).Select
End Sub
Which can also be written as:
Sub test()
Sheet1.Activate
Range([W12]).Activate
End Sub
A note on the .Value property - if you omit this, the value will usually be assigned anyway because it's the default property of the range object. That being said there are scenarios where this won't be the case and therefore it's always best practice to explicitly state that you want the value.
you most probably typed "R2:R11" in W12 cell, i.e with double quotes too
in that cell you only have to type R1:R12
moreover you can simply code
Sub test()
Sheet1.Range(Sheet1.Range("W12")).Select
End Sub

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.