Syntax Error with Named Range - vba

I cannot seem to get the syntax corrects as follows:
Sheet(DCRLog) has a named range at AE365 called EndSrtRnge
I am trying to sort the spreadsheet From A3 to AE365
Dim StSrtRnge As Range
Set StSrtRnge = Range("A3")
Dim NdSrtRnge As Range
Set NdSrtRnge = Range("EndSrtRnge")
Dim SortRnge As Range
Set SortRnge = Range(StSrtRnge:NdSrtRnge)*********Syntax Error
The final Statement used is
SortRnge.Sort Key1:=SortKey, Order1:=xlAscending, Header:=xlYes

You should use :
Set SortRnge = Range(StSrtRnge,NdSrtRnge)
Or with your syntax, you need :
Set SortRnge = Range(StSrtRnge.Address & ":" & NdSrtRnge.Address)

Range expects two cells separated by a comma or a string address.
Currently RANGE("A3") and Range("EndSrtRnge") may be on different sheets if the wrong sheet is acitve when Range("A3") is set - you haven't specified the sheet it's on.
Sub Test()
Dim NdSrtRnge As Range
Set NdSrtRnge = Range("EndSrtRnge")
Dim StSrtRnge As Range
'Ensure the start range is on the same sheet as the named range.
'Using just RANGE will place it on the currently active sheet.
Set StSrtRnge = NdSrtRnge.Parent.Range("A3")
Dim SortRnge As Range
Set SortRnge = NdSrtRnge.Parent.Range(StSrtRnge, NdSrtRnge)
End Sub
Just double checked - setting EndSrtRnge on Sheet1 and then selecting Sheet2 before running the code produced an Application-defined or object-defined error when using just Range("A3").

Related

Setting range on other sheet, based on abstract row number

With a sub on sheet1, I need to get data from a range of cells (P.. to W..) from row X, where X is take from a reference cell on sheet2.
Dim final_range As Range
Dim ref_cell_range As Range
Dim ref_cell As Range
Set ref_cell_range = Worksheets("sheet2").Range("O9:O15")
For Each ref_cell In ref_cell_range
Set final_range = Worksheets("sheet2").Range(Cells(ref_cell.Row, "P"), Cells(ref_cell.Row, "W"))
Next ref_cell
This code works if I leave out the 'Worksheets("sheet2").' part, but then it takes the cells from sheet1.
If I run it like this (refencing the sheet to take the range from), I get an error ('Run-time error '1004': Application-defined or object-defined error')
Does anybody know what I might be doing wrong?
Your final_range reference is looking at two sheets.
This is looking at Sheet2:
Worksheets("sheet2").Range(
This is looking at whichever sheet is active as you haven't qualified the sheet for Cells to reference:
Cells(ref_cell.Row, "P"), Cells(ref_cell.Row, "W")
The full line should be:
Set final_range = Worksheets("sheet2").Range(Worksheets("sheet2").Cells(ref_cell.Row, "P"), Worksheets("sheet2").Cells(ref_cell.Row, "W"))
or using With...End With:
Sub Test()
Dim final_range As Range
Dim ref_cell_range As Range
Dim ref_cell As Range
With ThisWorkbook.Worksheets("sheet2")
Set ref_cell_range = .Range("O9:O15")
For Each ref_cell In ref_cell_range
Set final_range = .Range(.Cells(ref_cell.Row, "P"), .Cells(ref_cell.Row, "W"))
Next ref_cell
End With
End Sub

Assigning two ranges from separate sheets to a variable

I have 3 worksheets and I am trying to assign a range to a variable on one of the sheets, based on ranges in two other different worksheets. Here is my code:
Sub Combine()
Dim range1 As Range
Dim range2 As Range
Dim ID As Range
Set range1 = Worksheets(3).Range("A2:A")
Set range2 = Worksheets(4).Range("A2:A")
Set newRng = Worksheets(6).Range(range1, range2)
End Sub
I'm getting back a
Run-time error '1004'
Any suggestions?
A range can't span multiple worksheets.
This may work, depending on what you ultimately need to do:
Set newRng = Worksheets(6).Range(range1.Address, range1.Address)
But, since these ranges have the same address in your example, I think what you want is not a Range object combining them, but some other data structure, like an array, collection, or dictionary.
NOTE Your ranges are not valid to begin with, Range("A2:A") is not valid, so you'll need to fix that. See here for reliable ways to find the "last" cell in a range. I've modified it to bring in the entire column A (except A1) but you will probably want to fine-tune that.
newRange will have to be a different data type for this to work without raising a Mismatch error, for example a Collection:
Sub Combine()
Dim coll as New Collection
Dim range1 As Range
Dim range2 As Range
Dim ID As Range
coll.Add Worksheets(3).Range("A2:A" & Rows.Count)
coll.Add Worksheets(4).Range("A2:A" & Rows.Count)
Set newRng = coll
End Sub
Or as an array of range:
Sub combine()
Dim newRange(1) As Range
Set r1 = Worksheets(3).Range("A2:A" & Rows.Count)
Set r2 = Worksheets(4).Range("A2:A" & Rows.Count)
Set newRange(0) = r1
Set newRange(1) = r2
End Sub
Using the array example above, you can then assign the values to another location, modify as needed:
Worksheets(4).Range("B1").Value = newRange(0).Value
Worksheets(4).Range("B2").Value = newRange(1).Value

Unexpected change of excel formula coming out of VBA macro

I have the below VBA example code that should populate the SumSQ range with the same formula as I've defined in the code
=SUMSQ(RC13-RC11,RC16-RC14,RC19-RC17,RC22-RC20,RC25-RC23)/(MONTH(TODAY())-MONTH(DATE(2016,1,1)))
Sub Prep()
Dim Sh As Worksheet
Dim CBS As Range
Dim SumSQ As Range
'Set range from C3 to final row of column C
Set Sh = Worksheets("Sheet1")
With Sh
Set CBS = .Range("C6:C" & .Range("C" & .Rows.Count).End(xlUp).Row)
Set SumSQ = .Range("AV6:AV" & CBS.End(xlDown).Row)
End With
SumSQ.Formula = "=SUMSQ(RC13-RC11,RC16-RC14,RC19-RC17,RC22-RC20,RC25-RC23)/(MONTH(TODAY())-MONTH(DATE(2016,1,1)))"
End Sub
However, for some reason in the actual spreadsheet after running the macro, the actual formulate that is getting populated for all cells in the range is:
=SUMSQ(R[7]C[423]-R[5]C[423];R[10]C[423]-R[8]C[423];R[13]C[423]-R[11]C[423];R[16]C[423]-R[14]C[423];R[19]C[423]-R[17]C[423])/(MONTH(TODAY())-MONTH(DATE(2016;1;1)))
In case it's of relevance, my locale settings use ; instead of , in formulas
So I am posting this as an answer as well:
Can you change SumSQ.Formula to SumSQ.Formular1C1?

Copy and pasting information within a for loop

I would like to create a function that copies certain excel ranges in worksheets and paste these ranges into a "motherfile".
Now, I am trying with this code:
Sub ranges()
Dim month As Variant
Dim months As Variant
months = Array("V01 DEN HAAG", "V02 AMSTERDAM")
Dim destinationRange As Excel.range
Set destinationRange = Sheets("DATASET").range("B3").End(xlDown).Offset(1, 0)
For Each month In months
Dim sourceRange As Excel.range
Set sourceRange = Sheets(month).range("H7", range("H7").End(xlToRight))
Call sourceRange.Copy
Call destinationRange.PasteSpecial
Next month
End Sub
But, I get an Application-defined or object-defined error. Any thoughts on what goes wrong? Thanks!
Adding to mielk's anwser the problem is in the codeline:
Set sourceRange = Sheets(month).range("H7", range("H7").End(xlToRight))
This is because if you are collecting from multiple sheets data and you use range("H7").End(xlToRight it will search for this on the active sheet. Therefor it can only find the correct range if its on the correct sheet.
by using the following code:
Set sourceRange = Sheets(month).Range("H7", Sheets(month).Range("H7").End(xlToRight))
it will work no matter which sheet is active at that moment.
another addition is you can copy and paste in 1 code line:
sourceRange.Copy Destination:=destinationRange
see below the entire code:
Sub ranges()
Dim month As Variant
Dim months As Variant
months = Array("V01 DEN HAAG", "V02 AMSTERDAM")
For Each month In months
Dim sourceRange As Excel.Range
Dim destinationRange As Excel.Range
With Sheets("DATASET")
Set destinationRange = .Cells(.Rows.Count, 2).End(xlUp).Offset(1, 0)
End With
Set sourceRange = Sheets(month).Range("H7", Sheets(month).Range("H7").End(xlToRight))
sourceRange.Copy Destination:=destinationRange
Next month
End Sub
The possibly reason for this error is that you don't have any values in worksheet "DATASET", column B, below 3. row.
Look at this line of code:
Set destinationRange = Sheets("DATASET").range("B3").End(xlDown).Offset(1, 0)
First it takes the range from cell B3 to the last cell in this column (B1048576 in Excel 2007+).
After that it tries to offset this range by one row down (so it tries to create a range having the same number of rows and columns but starting one cell below).
However, it is not possible, because such range would have to start in cell B4 and end in cell B1048577 and Excel has only 1048576 rows.
If you want to assign the first empty row to the variable destinationRange you should replace this code:
Set destinationRange = Sheets("DATASET").range("B3").End(xlDown).Offset(1, 0)
with the below:
With Sheets("DATASET")
Set destinationRange = .Cells(.Rows.Count, 2).End(xlUp).Offset(1, 0)
End With
Both those statements are similar. The difference is that the second one
starts from the last cell in the column B and look for the first non-empty
cell above.

Find last cell with function output data and output new result

This problem uses the following data, which would be manually adaptive over a fixed cell range--with each cell in the B column range containing a formula. It aims to find the last data cell from the underlying formula cells.
I would like to find the last formula cell with data within the formula range B2:B11, and create a dynamic median from this last cell with the four cells above it. The median should be output to cell F6--result of 9. This is a dynamic exercise. Any thoughts on how to do this most efficiently, given the code below?
Sub OutputMedian()
Dim FunctionRange As Range
'Represents a fixed range with function in B2:B11
Set FunctionRange = Worksheets("Sheet1").Range("B2:B11")
'Must start median calc from B9, as it's the last cell with function output data
'Must store Median from last data cell, using 5 cell offset (see output from cell F2)
'Must output the Final (e.g., median output of 9 here) to cell F6
End Sub
See: Excel VBA: Get Last Cell Containing Data within Selected Range
My modified answer by #brettdj from above question (referred by #varocarbas). Thanks!
Got it to work!! Outputs the correct dynamic median, with five periods set from -4 Offset below.
Sub OutputMedian()
Dim WS As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Set WS = Sheets("Sheet1")
Set rng1 = WS.Columns("B:B").Find("*", Range("B1"), xlValues, , xlByRows, xlPrevious)
Set rng2 = rng1.Offset(-4, 0)
Dim FirstCell As String
Dim LastCell As String
FirstCell = rng2.Address(0, 0)
LastCell = rng1.Address(0, 0)
Dim CellResponse As String
CellResponse = Evaluate("=median(" & FirstCell & ":" & LastCell & ")")
Range("F6").Value = CellResponse
End Sub
Better way to use objects (e.g., R1C1, Cells) in creating dynamic functions--i.e, without passing function into Evaluate as concatenated strings?