VBA storing a range in a cell - excel

I have a problem in VBA where I store a cell address as a range contained in a global variable. Problem is, any error and it stops working as it loses the variable. I'm trying to catch as many errors as I can, but I'd prefer to store the range in a cell if possible.
Does anyone have any suggestions?
Thanks
James

I would store the range in a Defined Name:
Assuming the name is called CellAddr and it already exists
Names("CellAddr").RefersTo = "=" & Worksheets("Sheet2").Range("A3:B8").Address(True, True, xlA1, True)
Then you can retrieve the range values or range address using the defined name.
You can also hide the name if you want, and it will persist in a saved workbook

I think something like this is what you are looking for, the Address property of Range returns the string of the Range
Edit: have ammended to show the name of the Worksheet
Public oRng As Range
Sub storeRange()
Dim oWst1, oWst2 As Worksheet
Dim oCell As Range
Set oWst1 = Application.Worksheets("Sheet1")
Set oWst2 = Application.Worksheets("Sheet2")
Set oCell = oWst1.Range("A1")
Set oRng = oWst2.Range("B2")
oCell.Value = oWst2.Name & "!" & oRng.Address
End Sub

Related

How to get range assigned to Named Range in excel vba?

I have already defined the named ranges in my workbook. I want to use the range for placing my pie chart. I am trying to write a code which sets range to variable and move the chart to the specific location.
Dim Rng As Range
Dim ChtObj As ChartObject
Set Rng = ThisWorkbook.Name("BT_GATE1").RefersTo
Set ChtObj = ActiveChart.Parent
ChtObj.Top = Rng.Top
I think I am missing something or using a worng method. Can some one help me assigning a range to variable 'Rng'?
A named range is either one cell or a collection of more cells which have been given a name. Ultimately it is a range. So in your case you can directly set it to a range as shown below
Dim Rng As Range
Set Rng = Range("BT_GATE1")
Debug.Print Rng.Address
Debug.Print Rng.Top
Debug.Print Rng.Parent.Name

how to find a value in a range in worksheet code

I need to find a value that the user inputs in one cell, in a range of values in the same workbook. In the worksheet, the user selects a value and then I need to write a code that finds that value in the range or delivers an error message. I was directed to put this in the worksheet code.
I tried specifying the worksheet of the criteria value but that hasn't seemed to make a difference as I am still getting the same error.
Range("Dcust").Offset(2, 0).End(xlDown).End(xlToRight).ClearContents
Dim shuttleNum As Range
Set shuttleNum = Range("Dsched").Offset(2, 0).End(xlDown).End(xlToRight)
Set driverSheet = ActiveWorkbook.Sheets("Driver")
Dim DSnumView As Integer
DSnumView = driverSheet.Range("DSnumView").Value
'''''Here is where I get the error'''
If shuttleNum.Columns(2).Find(DSnumView, lookat:=xlWhole) Is Nothing Then
MsgBox "You are not scheduled to drive this shuttle", vbCritical, "Error"
Exit Sub
Else
Dim ctable As Range
Set ctable = Range("CTableStart").Offset(1,0).End(xlDown).Range("CTableStart").Offset(0, 3)
End If
This line of code:
Range("Dsched").Offset(2, 0).End(xlDown).End(xlToRight)
returns a single cell.
So basically shuttleNum is set to a single cell and consequently this: shuttleNum.Columns(2) will give you an error because there is only one column in this range.
If I understand correctly what you're trying to do, the folowing should help.
Let's assume you have some data which starts from cell A1 but you don't know where it ends. For example:
To get the range that contains the data, which in this case is A1:C5, you would need to do the following:
Dim sht As Worksheet
Dim rng As Range
Set sht = ThisWorkbook.Worksheets("Worksheet Name")
Set rng = sht.Range("A1")
Set rng = sht.Range(rng, rng.End(xlToRight)) 'A1:C1
Set rng = sht.Range(rng, rng.End(xlDown)) 'A1:C5
Alternatively you can merge the last two steps into one:
Set rng = sht.Range(rng, rng.End(xlToRight).End(xlDown))

How can I pass the string value inside the Range as a reference?

I have one Excel Datasheet which consists of details about a particular product. Here I have written a VB script which pinpoints to a particular product using the unique product name which I have assigned for all the individual products.
When I run the below code:
Private Sub CommandButton23_Click()
Dim rngX As Range
Dim num As String
Set rngX = Worksheets("Sheet1").Range("A1:A10000").Find("CTPT", lookat:=xlPart)
num = rngX.Address
Range("$A$13:B" & Range("B2").End(xlDown).Row).Copy
Range("F1").PasteSpecial (xlPasteValues)
End Sub
Here in the above code I am getting where the Product "CTPT" is located, the address of the cell location is stored in "num".
How can I assign the "num" cell address $A$13 in the range function so that I can select all the parameters related to that particular product and it will get copied and pasted in F1 cell.
You are correct in that you will start with the rngX that was located with the Range.Find method, but you do not need to resolve that to a Range.Address property that is subsequently used to reference a Range object. Using rngX as a Range.Object can generate the starting cell and rngX.Row can help get the lower left cell of the Range.Copy method.
Private Sub CommandButton23_Click()
Dim rngX As Range
Dim num As String
Set rngX = Worksheets("Sheet1").Range("A1:A10000").Find("CTPT", lookat:=xlPart)
Range(rngX, Range("B" & rngX.Row).End(xlDown)).Copy
Range("F1").PasteSpecial (xlPasteValues)
End Sub
Like this?
Range(num & ":B" & Range("B2").End(xlDown).Row).Copy
Or, without the intermediary num variable:
Range(rngX.Address & ":B" & Range("B2").End(xlDown).Row).Copy
I would advise that Range("B2").End(xlDown) may not be ideal, it is particularly unreliable when working on data with non-contiguous areas as in your screenshot.

Using Match and Address functions within Macro or VBA

I have two worksheets, I want to use a value in sheet to_approve to lookup against column A in sheet submitted, then identify the cell reference so I can paste a value in the cell adjacent (column B).
I have used the following to identify the cell reference, but I don't know how to use it in VBA code.
=ADDRESS(MATCH(To_Approve!D19,Submitted!A:A,0),1,4,1,"submitted")
While many functions can be used in VBA using Application.WorksheetFunction.FunctionName ADDRESS is not one of these (MATCH is)
But even it it was available I would still use a Find method as below as it:
gives you the ability to match whole or part strings, case sensitive or not
returns a range object to work with if the value is found
readily handles a no match
you can control the point in the range being search as to where the search starts
multiple matches can be returned with FindNext
something like
Sub GetCell()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("submitted")
Set rng1 = ws.Columns("A").Find(Sheets("To_Approve").[d19], , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox rng1.Address & " in sheet " & ws.Name
Else
MsgBox "not found", vbCritical
End If
End Sub
This example should give you an idea of how to find a corresponding value on another sheet and place a second value in the the column to the left. When using VBA, it is not necessary to select cells and then paste; you can directly enter a value into a range (cell) object.
Sub TransferValue()
Dim rngSearch As Range
Dim rngFind As Range
Dim dValue As Double
' initialization
Set rngSearch = Worksheets("to_approve").Range("D19")
dValue = Date
' find the match & insert value
Set rngFind = Worksheets("submitted").Columns(1).Find(What:=rngSearch.Value)
If Not rngFind Is Nothing Then
rngFind.Offset(ColumnOffset:=1).Value = dValue
End If
End Sub
(Note: dValue is a placeholder for whatever value you want to enter.)

Problems trying to set RefersToRange property in Excel VBA

I was helping a friend work out a problem with VBA in Excel 2007 today, and we ran into an issue I think I'd encountered and worked around in the past. It's an issue with changing the range to which a name refers.
On my friend's main worksheet, in B7, she has data validation from a List where the Source is a named range, CAT_LOOKUP. She wanted to run a sub that would filter a table on another worksheet to show only rows that correspond to the value in B7 and then use those rows as the source for validation in another cell on that worksheet.
Here's the relevant part of the VBA we were using:
Dim strCAT As String
Dim strACT As String
Dim sh As Worksheet
Dim rng As Range
Dim rngDest As Range
If Cells(7, 2) <> "" Then
strCAT = Cells(7, 2).Value
Sheets("CAT LOOKUP").Range("$A2:$C393").AutoFilter Field:=1, _
Criteria1:=strCAT
Set sh = Sheets("CAT LOOKUP")
Set rng = sh.Range("B34:B56")
rng.ClearContents
Set rng = sh.Range(sh.Range("B1"), sh.Range("B1").End(xlDown))
rng.Copy
Set rngDest = sh.Range("B34")
rngDest.PasteSpecial
ActiveWorkbook.Names("CAT_LOOKUP").RefersToRange = _
sh.Range(sh.Range("B35"), sh.Range("B35").End(xlDown))
Else
Set sh = Sheets("CAT LOOKUP")
Set rng = sh.Range("B34:B56")
rng.ClearContents
Sheets("Ad Hoc Request").Select
End If
CAT_LOOKUP is already defined. When this code is run, the CAT_LOOKUP range is cleared, and the definition of the range is unchanged.
I found in my notes from an old project that I'd used RefersToR1C1 instead of RefersToRange, so I changed that line to this:
ActiveWorkbook.Names("CAT_LOOKUP").RefersToR1C1 = _
"='CAT LOOKUP'!R35C2:R" & sh.Range("B35").End(xlDown).Row & "C2"
and the code worked as desired, resetting the named range so that the corresponding data validation works properly.
Is this simply a bug in the implementation of RefersToRange, or is there a problem with the way we were using it?
RefersToRange is read-only, at least in XL 2003 and probably in 2007.

Resources