Excel VBA: How do I assign a range to a variable? - vba

The current code is as follows:
With Sheets(sheetChk)
a = .Range(chkCell, .Range(Left(chkCell, 1) & Rows.Count).End(xlUp)).Value
End With
sheetChk is defined as the desired sheet index.
chkCell is defined as the desired "first cell" in the range.
I am attempting to assign a range to a. The problem is that the above code grabs the last cell in the column, entirely. Rather, I want to end at a specific row as I have other data in the same column after the desired range that needs to be ignored. How can I accomplish this?

First to assign a range, you need to have a Set first.
Example: Set a = Range("A1")
Another problem I see is that you're putting a .value at the end. That doesn't make sense for a range.
If you want to specify a specific row, then you need to include that in the code instead of using end(xlUp).
Example if it's row 50:
With Sheets(sheetChk)
Set a = .Range(chkCell, .Range(Left(chkCell, 1) & 50).End(xlUp))
End With
What you're currently using is finding the bottom row being used, which doesn't sound like you want. If you want to go the other direction (i.e. from the starting cell down until there's an empty cell), you can use this code:
With Sheets(sheetChk)
Set a = .Range(chkCell, .Range(Left(chkCell, 1) & chkCell.Row).End(xlDown))
End With
Based on your code, it looks like you might be putting an address in whatever cell chkCell is. If you have the row in that cell, and assuming you never exceed column z, then you could use this code to find the row:
With Sheets(sheetChk)
Set a = .Range(chkCell, .Range(Left(chkCell, 1) & Right(chkCell,Len(chkCell)-1))
End With
If that doesn't work, you need to figure out some method determine what row to use. Hope that helps.

dim rng as range
set rng = thisworkbook.sheets("sheet1").range("a1:a666")

Related

Referencing indirect cells in excel VBA

So I am trying to have a cell reference in my code be an indirect reference. For instance I want to update the value in column B cell "X" where X is defined in cell B1.
Here is the code that I am currently trying but I keep getting an out of range exception. I am very new to VBA so my syntax could just be very far off.
Workbooks("Personal_Finances").Sheets(categoryType).Range("$B($B$1)").Value = ammount
Try,
with Workbooks("Personal_Finances").Sheets(categoryType)
.cells(.Range("B1").Value, "B") = ammount
'alternate
.Range("B" & .Range("B1").Value) = ammount
end with
Here .Range("B1").Value is used for the row reference in .Cells. The alternate is closer to what you were originally attempting.
I've wrapped the working code in a With ... End With block to maintain the parent worksheet reference.
There is no need for $ in a quoted string cell reference unless used in a formula populating multiple cells at once.
def a new variable and assign the value of cell $b$1 to it.
dim temp_row as integer
temp_row.value =Workbooks("Personal_Finances").Sheets("categoryType").Range("B1").Value
Workbooks("Personal_Finances").Sheets(categoryType).Range("$B" & temp_row).Value = amount
or just do the same thing in one line.
Or:
With Workbooks("Personal_Finances").Sheets(categoryType).Range("B1")
.Offset(.Value2 - 1) = ammount
End With
Where the “With ... End With” block references cell B1 of wanted worksheet in wanted workbook and the nested statement offsets it by its value minus one (to reach wanted row)

Copying Row Except Last Column in VBA

I am writing an Excel VBA macro and one of the tasks is to copy a subset of the data from a sheet to another.
I currently use the below, which copies the whole row fine (C is a row index):
Dim ConsolidatedRow As Excel.Range
Set ConsolidatedRow = ConsolidatedSheet.Range("A" & C).EntireRow
...
ConsolidatedRow.Copy Destination:=ResultSheet.Range("A" & ResultRowIndex)
I want to copy ConsolidatedRow, but without the last column. This last column is used in other operations between declaration and copy so the ideal solution would be a change to the copy statement. I've tried offsets, updating the range in ConsolidatedRow and loads of other things but no luck.
I prefer to use the Range.End property to locate the last used cell. Helps out if your row doesn't extend out as far as others in your sheet. Replace the Set ConsolidatedRow command with the following:
With ConsolidatedSheet
CopyExtent = .Range("A" & C).End(xlToRight).Column - 1
Set ConsolidatedRow = .Range(.Cells(C, 1), .Cells(C, CopyExtent))
End With
This assumes you have no gaps in your data. If you have blank cells that you want included in the copied section, change to this:
CopyExtent = ConsolidatedSheet.Cells(C, .Columns.Count).End(xlToLeft).Column - 1
Hope this helps!
Assuming that you don't use columns behind this consolidatedRow in this worksheet, add two lines after set
Set ConsolidatedRow = Intersect(ConsolidatedSheet.UsedRange, ConsolidatedRow)
Set ConsolidatedRow = ConsolidatedRow.Resize(1, ConsolidatedRow.Columns.Count - 1)

Copy rows based on cell value and paste on a new sheet

Check This
I need a help. I want to copy whole cell from A sheet name "Components" only if value in Column C is > 0 to a new Sheet name "Load list"
Can someone please give me the macro code for this?
on your new sheet you can add this condition the cell or range of cells:
=IF(Components!C5>0,Components!A5)
where C5 has thevalue to compare, and A5 has the value copy if the condition happens.
Right in my swing!
The formula given by #sweetkaos will work fine, in case you want to replicate the data as it is with blanks where data is not found.
I will imagine a slightly more complicated situation. I am assuming you want just one line in the next format as is shown in your image.
Also conveniently assuming the following:
a. both sheets have fixed start points for the lists
b. 2 column lists - to be copied and pasted, with second column having value
c. Continuous, without break source list
d. basic knowledge of vba, so you can restructure the code
Here is the code. Do try to understand it line by line. Happy Excelling!
Sub populateLoadList()
'declaring range type variables
Dim rngStartFirstList As Range, rngStartLoadList As Range
'setting values to the range variables
'you must change the names of the sheets and A1 to the correct starts of your two lists
Set rngStartFirstList = Worksheets("Name_of_your_fist_sheet").Range("A1")
Set rngStartLoadList = Worksheets("Name_of_your_second_sheet").Range("A1")
Do While rngStartFirstList.Value <> ""
If rngStartFirstList.Offset(1, 0).Value < 0 Then
Range(rngStartFirstList, rngStartFirstList.Offset(0, 1)).Copy
rngStartLoadList.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Set rngStartLoadList = rngStartLoadList.Offset(1, 0)
End If
Set rngStartFirstList = rngStartFirstList.Offset(1, 0)
Loop
End Sub
Basically what i want is ... if Value on C is >0 i want whole column 10 copied to that new sheet .... not only that cell

Variable Range Used for a Formula

I recorded the below code for use in my macro, but it would only be useful if that range never changes.
Because the range does change each time I run it, how can I change "A1:E2" into variables to account for a changing range?
I don't think xlLastCell would be a correct usage in this case.
I know how to get the column number and row number of the ending cell, but I couldn't figure out how to incorporate that into my code.
ActiveCell.Offset(2, 0).Range("A1:E2").Select
Selection.FormulaR1C1 = "0"
I know how to get the column number and row number of the ending cell, but I couldn't figure out how to incorporate that into my code.
Like this:
Dim myRange as Range
Set myRange = Range(Cells(1,1), Cells(lastRow, lastColumn))
myRange.FormulaR1C1 = "0"
In the above code, myRange is defined by two cells, one at (1,1) (row 1, column 1) and another at (lastRow, lastColumn) which would be the vairables you identifed as the ending row/column.

Finding average of selection and then assigning it to a cell

I am attempting to create some dynamic code that, at this point, will select a bunch of cells, move the selection over two columns, then find the average of that selection and send that value to a cell. This is what I have so far, I am getting stuck at averaging the selection I've made:
Sub StatMakersub(Rng1 As Range)
Dim MyRange As Range
Dim Cell As Object
Dim InQuestion As Range
Dim SelAvg As Object
'Check every cell in the range for matching criteria.
For Each Cell In Rng1
If Cell.Value = 2000 Then
If MyRange Is Nothing Then
Set MyRange = Range(Cell.Address)
Else
Set MyRange = Union(MyRange, Range(Cell.Address))
End If
End If
Next
'Select the new range of only matching criteria
MyRange.Select
Selection.Offset(0, 2).Select
Set InQuestion = Selection
Range("P2").Formula = "=Average(Selection)"
Range("Q2").Formula = "=STDDEVA(Selection)"
End Sub
I can't find much on the web about how to average range variables.
You can calculate the average of a selection in this way:
Application.WorksheetFunction.Average("Here you put your range")
The result is a value and not an object, so you should use a variable. Taking names from your case you should use it like this:
SelAvgResult = Application.WorksheetFunction.Average(InQuestion)
I put another name for the variable, but you may still use SelAvg if you like. Just remind to define it as a variable (you may choose your desired format depending on the data size) instead of object if you do not need it anymore.
You may use then this variable for setting the value of your desired cell.
I have a last note: your code seems to replicate the already existing formula AVERAGEIF. If your criteria column is for instance column A and value you should use for calculating the average are in column C, You could directly set the value of the cell where you want the average like this:
=AVERAGEIF(A:A, "2000", C:C)
In this case you would avoid VBA.
Have you tried using the Sum worksheet function for calculating the sum of the range?
Xsum = WorksheetFunction.Sum(arrayX)
and dividing the Xsum value with the length of the array?
One thing I should metion is that you do not need to select the range to work with it. You can use it directly and doing so will also improve how fast your code runs.
To insert your worksheet functions, use the Range.Address function to generate a cell reference to put into the formulas.
https://msdn.microsoft.com/en-us/library/office/ff837625.aspx