I have some VBA code that works on named ranges that are set up externally. How can I get the actual cell reference from this range? For example
Dim rangeID As String
rangeID = ActiveSheet.Range("MyNamedRange").UnknownFunction
Sets rangeID to "CG13" if the named range "MyNamedRange" refers to CG13
ActiveSheet.Range("MyNamedRange") already is the "actual cell reference." It references the cell object. You should directly use that object reference anywhere you need a cell in your code.
The textual representation of the address of that cell is ActiveSheet.Range("MyNamedRange").Address. You can provide parameters to get the address in the form you want (e.g. to get "CG13" you call Address(False, False, xlA1)).
Related
I'm trying to loop through the multiple named ranges, every range is just one cell, on a column, so it starts with item1, item2...item100.Each of these ranges has a cell reference in it (like "AM100").
I want to be able to set up a for/while loop that just selects(and does something) each of the referenced cells in those named ranges.
I'm stuck at VBA not considering "item"&"1" the same with "item"&"i" when i =1 and from what I deduct this is purely a data type issue. It's able to refer to a pure string range but when it's variant/string type (which any concatenation of string or converted string variable results in).
item1 range has in it $AM$10 reference. That cell, has a value in it. Eventually I want to change the values in multiple similar cells by referring to the name ranges that hold their reference.
Without the "for" loop, I've tested the following:
Sub test()
Dim i as integer
i=1
'These don't work
Range([indirect("item"&CSTR(i))]).Select
Range([indirect("item"&i)]).Select
'What works is, but this is not useful since I want to loop through i:
Range([indirect("item" & "1")]).Select
Range([indirect("item1")]).Select
Sub Test()
Dim oDefName As Name
For Each oDefName In ThisWorkbook.Names
If Left(UCase(oDefName.Name), 4) = "ITEM" Then
Range(oDefName.RefersToRange.Value).Select
End If
Next
End Sub
Note: There is no error checking to ensure that the value within the named range is actually a cell reference.
Edit- Above is how I would solve the problem. Indirect is an in cell function and not usable directly in vba. Below is how you would get the indirect functionality in VBA with a counter.
Range(Range("Item" & oCounter).Value).Select
I set up a named range, let's call him RngIn.
He has 3 cells, and his address refers to A1:A3
Next, I delete Row 2.
My RngIn now shows #REF! error (correctly) in its RefersTo property:
"=A1,Sheet1!#REF!,A2"
This means I cannot manipulate the rest of that named range using VBA, because of the Method 'Range' of Global Object error.
The range is created during a process, and if a user subsequently needs to delete one row for whatever reason, my future code will fail because it needs to know where the rest of the named range data is...
I have tried many ways to access the remaining address information for this range, in VBA, but failed so far, e.g.
Dim RngAddress As String
Dim RngIn As Range
Set RngIn = Range("A1:A3")
RngAddress = RngIn.Address
RngAddress = RngIn.RefersToRange.Address
RngAddress = RngIn.RefersTo
RngAddress = Replace(RngIn.Address, "Sheet1!#REF!", "")
What I ideally want to see in a text string as the result for RngIn is:
"=A1,A2"
Because A2 is now the location of the data which was originally in A3.
Not sure I understand this well: your example code does not use Defined Names (aka Named Ranges).
lets suppose you create a Name called RangeIn that refers to A1,A3,A5 and you then delete Row 3.
The RefersTo for RangeIn is now =Sheet1!$A$1,Sheet1!#REF!,Sheet1!$A$4
This code removes the Sheet1!#REF!, to leave the Name RangeIn referring to =Sheet1!$A$1,Sheet1!$A$4
Option Explicit
Option Compare Text
Sub ChangeRef()
Dim strAd As String
strAd = ThisWorkbook.Names("RangeIn").RefersTo
strAd = Replace(strAd, "Sheet1!#REF!,", "")
ThisWorkbook.Names("RangeIn").RefersTo = strAd
End Sub
In cases like this, I set the start and end points of my named ranges to be the cell above and the cell below the range where the user can delete, and then use the OFFSET or INDEX function to resize that range to exclude my bookmarks. Or I use Excel Tables, which can handle row deletions without returning #REF errors.
How do I reference/select a named range based on a string variable with the text being the name ranged name?
Example:
'Target is range variable which is set to cell that is double clicked.
'For this example lets say the cell value is "A1A"
Dim binName As String
binName = "B1" & Target(1).Value
MsgBox(binName) 'This displays "B1A1A" which is the name of the named range
Range(binName).Select 'I want to select the range with the name B1A1A
This gives me
Run-time error '1004':
Method 'Range' of object'_Worksheet' failed
on the last line of the above code.
I understand that Range() is looking for an object, but I dont know how to refer call a range name from a string variable.
Thank in advanced for any help.
Resolution Edit:
Per Davids recommendation below, I changed
Range(binName).Select
to
Application.Goto ThisWorkbook.Worksheets("B1").Range(binName) 'where "B1" is the worksheet name
It's possible to have a Workbook scoped range that is still explicitly assigned to a single worksheet, which I gather is what you want (Name refers to some range on some other worksheet, etc.).
If you're doing this as UI, rather than Select try using the following:
Application.GoTo Range(binName)
Or:
Application.GoTo [binName]
Tested, and seems to work even when a range is explicitly on another worksheet, Application.GoTo takes care of toggling to that sheet and selecting that range.
Application.Evaluate(binName).Select
Application Evaluate will evaluate a string and resolve the reference. It accepts strings as arguments, and doesnt need to resolve to a range (for example, Application.Evaluate("10") would result in a return of 10).
For more information, check out the MSDN documentation: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-evaluate-method-excel.
EDIT: Worth noting, this isnt properly error handled, so it could potentially return a Nothing reference, or an error, if the input string is not a valid named range.
Additionally, ThisWorkbook.Sheets("SomeRangeName").Select should work (and does work) just fine. It is more likely that there is something wrong with the name of your range.
Situation: I'm using Excel 10. I have a named variable that uses a formula to compute it's value. This is a named variable, not a named range (in the 'Name Manager' the name "MaxDate" refers to "=MAX(Sheet1!B:B)" where column B is a list of dates). The computed value does not appear in any cells by itself, but rather is used in various formulas within the spreadsheet.
My problem: How can I reference this named variable in VBA code? Using range("MaxDate").value does not work. I know I can simply put the value into a cell and reference the cell, but I'd like to find a way to reference the variable directly. Any ideas?Thanks.
Here's some examples of working with your named variable:
Sub TestNamedVariable()
Dim varFormula As String
Dim varValue As Variant
'This will print the formula if you need it:
varFormula = ActiveWorkbook.Names("MaxDate")
'This will evaluate the named variable/formula
varValue = Application.Evaluate("MaxDate")
End Sub
For a given workbook with a Named variable "MyVar", valued "=MAX(Sheet1!B:B)".
Try the following code:
Evaluate(ActiveWorkbook.Names("MyVar").RefersTo)
Replace the ActiveWorkbook with the object you're referring if you need to.
I am writing an application in VBA for excel. Using some conditions and counting the number of records by the following functions which is working fine.
cnt = appExcel.Application.CountIfs(R1, AuditType, R2, "Fail", UserRange1, UserName & "*")
Here R1,R2 and UserRange1 are Range types which is describing individual cells.
If we print
R1.Address '$E:$E
R2.Address ' $M:$M so on.
I am getting the number of rows present with those criteria in "cnt" variable.
I need further manipulation like searching some custom cells from the above range of cells. To do that I need to store those addresses in a "Range" object.
Please guide me how can I store those filtered records in a range. I don't want to copy to another area also.
You add a new range to a worksheet by declaring a Name object in VBA and then setting it's RefersTo value to the address. This example adds the needed declarations and code to do this. It assumes that you are interested in the cells in your R1 range which contain constants:
Dim rngFiltered As Excel.Range
Dim nmNew As Excel.Name
'...
Set rngFiltered = R1.SpecialCells(xlCellTypeVisible)
Set nmNew = ws.Names.Add(Name:="NewRange", RefersTo:="=" & rngFiltered.Address)
If I am understanding what you mean, insert a named range which defines the range referenced.
Excel 2003 Insert>Name>Define
Excel 2010 Formulas>Define Name