finding sum of squares of column using for each - vba

I am a newbie. I want to sum the squares of the numbers in the active column. I am getting an error 'object doesn't support this method'. Here is my code
Sub sum_squares()
Dim total As Integer
Dim c As Range
Dim d As Range
'set d equal to column from active cell down to last non-empty'
d = Range(ActiveCell, ActiveCell.endxldown)
total = 0
For Each c In d
total = total + c.Value ^ 2
Next c
End Sub
Appreciate the help.
Thanks

As has been pointed out you've got the syntax of xlDown incorrect.
You should also start at the bottom and move up - xlDown may not find the last cell.
E.g.
With a value in cell A1:A3 and A1 as the ActiveCell it will correctly return A3.
Same scenario but with A4 left blank and a value in A5 still returns A3.
Same scenario with A1 left blank it returns A2.
This will return a reference from the ActiveCell to the last cell containing a value in that column.
Note that if the ActiveCell is lower down than the last cell containing data you'll get a reference reflecting that.
Set d = Range(ActiveCell, Cells(Rows.Count, ActiveCell.Column).End(xlUp))
A Range can be made up of one or more cell references:
Range("A1") and Range("A1,A3,C5") reference individual cells.
Range("A1:C5") and Range("A1", "C5") reference all cells between the first and last address.
A Cell is a single cell reference that uses row and columns identifiers.
Cells("A1") will return an error as it's a full address.
Cells(1,"A") will return A1 (row 1, column A)
Cells(1,1) will also return A1 (row 1, column 1)
The code above is using two cell addresses to reference all cells between the two.
Range(ActiveCell,....) is the reference to the first cell.
Cells(Rows.Count, ActiveCell.Column) is the reference to the second cell using row numbers and column numbers.
If the ActiveCell is in column B then this is the same as writing Cells(1048573,2).
The End(xlUp) then goes from that cell back up to the first one containing data.

There is a syntax error in your code - .endxldown and add Set before assigning range.
Correct it to -
Set d = Range(ActiveCell, ActiveCell.End(xlDown)

Related

How to autofill a range in VBA with differing variables

I am trying to figure out how to autofill a specific range of cells based on already defined data in the same row. My task is more complex, but a simplification of the step can be seen in the code below. What I want to achieve is:
Define a range where I want to output my values
Multiply two values in the same row of the selected range cell (to its left), and output this number in the currently selected range cell. To do this, one of the numbers to be multiplied will be dependant on a string also in the row (which describes its type).
Loop through the defined range and repeat the calculation on each row.
My current code is as follows and outputs a "application defined or object defined error".
Any help would be much appreciated.
For a = Range("P12") To Range("P33") 'Range of cells I want to fill.
If Cells(a, -10).Value = "B" 'If the cell 10 to the left of our "a" value is = "B".
Then c = Cells(a, -10).Value * Worksheets("LCI").Range("D4").Value 'Then new variable "c" = (cell 9 to left of a) * (number from another sheet containing a database)
Cells(a).Value = c 'Update value of selected range cell to contain c which we calculated.
Next 'Repeat for all rows in range.
You are close.
You need to think of a as a cell or Range object. That variable is the cell itself which has properties like a.row and a.column that describe its location on the sheet in which it lives.
When you say Cells(a, -10) you are saying "On the Activesheet I want a Cell where the row is a, and where the column has the number -10". There is no row a (as a is a range/cell object and because you didn't specify which property of a you are wanting here it will default to a.value which is probably nothing) and there is no column -10 on the Activesheet.
Your loop is defined incorrectly. You can use a For Each loop to loop through cells in a range.
Instead:
For Each a In Range("P12:P33")
'clear `c` each loop
c=0
If a.Offset(,-10).Value = "B" Then 'start at cell `a` and move back 10 columns and grab the value
c = a.Offset(, -10).Value * Worksheets("LCI").Range("D4").Value
End If
a.Value = c
Next a

Showing Numbers inbetween two numbers on the same row

What I'm trying to achieve is there are 2 whole numbers in column A & B on the same row. I want to fill the row from Column C to show the whole numbers increments of one between the two numbers.
i.e.
A B C D E F G H I J K L
1 10 1 2 3 4 5 6 7 8 9 10
any help would be appreciated.
Assuming this is Excel and you can open the VBE Editor to use VBA
Here's a macro you can run or call via a button
See the comments in the code to understand what it's doing with the Dataseries fill function
Sub FillData()
Dim intStopAt As Integer
' Set to cell indicated low end of range
Cells(1, 1).Select
' Fill in "Start At" Number
ActiveCell.Offset(0, 2).Value = ActiveCell.Value
' Retrieve and use stop number to fill in series
intStopAt = ActiveCell.Offset(0, 1).Value
ActiveCell.Offset(0, 2).DataSeries Rowcol:=xlRows, Type:=xlLinear, Date:=xlDay, Step:=1, Stop:=intStopAt
End Sub
The below code assumes you have no header and that your value in A1 is always 1, and your value in B1 is the number you want to count to.
This can be modified to be more dynamic, but taking your question as is, this should work for you.
1) Check number to count to (CountTo)
2) Run loop for 1 to CountTo and auto-populate your column headers
To run: Open VBE and paste this code on the sheet where you wish to run it.
Sub Counter()
Dim CountTo As Integer
CountTo = Range("B1").Value
For i = 1 To CountTo
Cells(1, i + 2) = i
Next i
End Sub
This can be done without VBA, perhaps not as neat initially as #dbmitch's answer because the formula has to go across to the maximum possible number.
A1 is start number, > 0
B1 is end number (> A1)
In Cell C1 enter =A1
In Cell D1 enter =IF(AND(C1<$B1,C1>=$A1),C1+1,"") and then
drag/fill right as far as you need to.
I have formulated the code so that you can now select the filled rows (A through to wherever) and fill down.
A simple explanation:
C1 sets the start of the list
The AND formula in D1 onwards checks that the immediate left cell (for D1 this is C1, for E1 this is D1 etc.) is less than the end number and greater than the start number.
If the conditions are true, use the immediate left cell value + 1 as the result.
If the conditions are false, insert a blank.
Further checking can be done, I have assumed in the above solution that the numbers are positive and increasing.
You can use helper columns to indicate if you should increase or decrease (i.e. +1 or -1 as required.
Using a blank as the other answer falls down if the numbers go from -ve to +ve. In this case, you could use another symbol (e.g. x) and check for that in the AND function as well.
you could use this:
Sub main()
Dim cell As Range
With Range("A1", Cells(Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants, xlNumbers) ' reference column A cells from row 1 down to last not empty one with a "constant" (i.e. not a formula result) numeric content
For Each cell In .Cells 'loop through referenced range
cell.Offset(, 2).Resize(, cell.Offset(, 1).Value - cell.Value + 1).FormulaR1C1 = "=COLUMN()-COLUMN(C3)+RC1" 'write proper formula in current cell adjacent cells
Next
.CurrentRegion.Value = .CurrentRegion.Value ' get rid of formulas and leave values only
End With
End Sub

Excel VBA Autofill across columns

I want to edit the range in Autofill code below but I'm not sure how.
'find last used cell in the row to the right
Range("B59").End(xlToRight).Select
'auto fill the formula for "Total TV"
ActiveCell.AutoFill Range(ActiveCell, ActiveCell.Offset(0, 1))
At present, the code finds the last valid cell in a row, then it autofills one cell to the right.
What I want to do:
I would to find the last valid cell, then select the active cell and the cells from 3 rows below it too and then autofill one cell to the right.
In pictures it would look like this:
find last valid cell in row 59:
select active cell and cells 3 rows below:
Autofill one cell to the right
Here is one way. No need to Select
Sub x()
Dim r As RANGE
Set r = RANGE("B59").End(xlToRight)
r.Resize(4).AutoFill r.Resize(4, 2)
End Sub

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

VBA Delete row based on 2 columns

I have some VBA code that will delete the entire row if a cell in a column has red text
Dim Cell As Range
For Each Cell In Intersect(Columns("L"), ActiveSheet.UsedRange)
If Cell.DisplayFormat.Font.ColorIndex = 3 Then Cell.Value = "#N/A"
Next
On Error GoTo NoRedText
Columns("L").SpecialCells(xlConstants, xlErrors).EntireRow.Delete
NoRedText:
I would like to extend this code to also include another column that includes a "Y" value in the cell.
Column L includes the red text string
Column P includes the "Y" text string
Therefore if the text is red in column L AND the text is equal to "Y" in column P it should delete the entire row
What do I need to add to the code to achieve this?
Thank you
Your Cell variable references a range and all the properties that go with it.
The Offset property
Returns a Range object that represents a range that's offset from the
specified range.
(https://msdn.microsoft.com/en-us/library/office/ff840060.aspx)
Using this knowledge you can tell your code to look at the range that is offset by four columns:
If Cell.DisplayFormat.Font.ColorIndex = 3 AND Cell.Offset(,4)="Y" Then Cell.Value = "#N/A"