Looping through cells, building a range in VBA - vba

I am looking to loop through cells and build a range for a graph. My main issue is that I cannot figure out how to incorporate the 'i' into the range. Example:
Dim name As String
Dim newChart as Chart
Dim i as Integer
Set newChart = Charts.add
For i = 1 To 20
accName = Range("C" & i).Value 'I understand why this works.
With newChart
.ChartType = xlColumnClustered
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = accName
.SeriesCollection(1).Values = wb.Worksheets("Summary-Account").Range("E&i:G&i, I&i:K&i, M&i:O&i, Q&i:S&i") 'How can I get this to work?
.SeriesCollection(1).XValues = wb.Worksheets("Summary-Account").Range("E3:G3, I3:K3, M3:O3, Q3:S3")
End With
i = i + 1
Loop

You don't increment manually i.
The function for loop already does it for you.
So remove that i = i + 1.
Now, to make your Range work, you would need its "" to be something like this : Range("E" & i & ":G" & i). I don't quite understand what you are trying to achieve with trying to take data from 6 different columns.. See range for further information.

You probably need to have:
.SeriesCollection(1).Values = wb.Worksheets("Summary-Account").Range("E" & i & ":G" & i & ", I" & i & ":K" & i & ", M" & i & ":O" & i & ", Q" & i & ":S" & i)
Not the clearest line ever, but should give you the pattern to go by. There are other problems like needing a "Next i" instead of a "Loop" and no i=i+1, but on my computer this gave me a graph with multiple series on it.

Try
.SeriesCollection(1).Values = Range("E1").Resize(20,1).Value
this will copy all the values into an array for use in series collection

use Next i instead of Loop; and get rid of that i = i+1.
Also, use "E" & i & ":G" & i instead of "E&i:G&i"
One step further, in vba
Dim i as double
For i = 1 to 100 Step 10 '<= Step 10 means when updating i, i = i + 10, and default value would be 1
Loop '<=breaks here, compile error is expected.
this is not even valid in syntax, the keyword Loop is associated with another keyword Do, and For is associated with Next

Related

VBA -- variable in .formula

is there a more elegant (simpler) way to put a variable in .formula? I don't want to use .formulaR1C1
I have this code:
Range("C8").Select
Selection.End(xlDown).Select
PosR = ActiveCell.Row
KonR = PosR - 2
Range("N" & PosR).Select
aAddress = Range("$N$9").Address & ":" & Range("$N$" & KonR).Address
ActiveCell.Formula = "=SUM(" & aAddress & ")"
Obviously I want to put =SUM($N$9:$N$101) (101 is the last cell minus 2) into that cell and this code does the job. But I just want to be sure that this is the easiest way to do this.
The easiest way is to skip all that selecting and those variables
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Edit: to be more explicit, the easiest way is to use FormulaR1C1 but you said you didn't want to, so...
You can use the code below (without using Select and ActiveCell:
PosR = Range("C8").End(xlDown).Row
KonR = PosR - 2
Range("N" & PosR).Formula = "=SUM(" & Range("$N$9").Address & ":" & Range("$N$" & KonR).Address & ")"
Or, the much simplier version:
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & KonR & ")"
Well you should be trying to avoid using Select in VBA. You've made the actual inclusion of a variable in the .Formula about a simple as it gets, but your whole code could be simplified:
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Really you should be fully qualifying your ranges too, like so
With ThisWorkbook.Sheets("Sheet1")
PosR = .Range("C8").End(xlDown).Row
.Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
End With
And if you have blank cells in column C then your use of xlDown will fail to find the last cell. You may want to look at ways of finding the last cell in VBA or simply use
' Again, preferably fully qualified
Range("C" & Rows.Count).End(xlUp).Row
Range("$N$9").Address gives exactly "$N$9".
Range("N9").Address gives the same. Thus, it is a bit overwork. Check out the first two debug.print in the sample below.
Thus, once you calculate the last row and assign value to it lngLast, it is possible to get the formula like this:
"=SUM(N9:N" & lngLast & ")"
Option Explicit
Public Sub TestMe()
Dim strA As String
Dim lngLast As Long
strA = Range("$N$9").Address
Debug.Print strA = "$N$9"
strA = Range("N9").Address
Debug.Print strA = "$N$9"
lngLast = Range("N" & Rows.Count).End(xlUp).Row - 2
ActiveCell.Formula = "=SUM(N9:N" & lngLast & ")"
End Sub
Good morning, everyone :)

vba specialcells visible define range

I am trying to use the SUM function to add all of the visible cells in column I from sRow to dRow (variables are starting and ending rows for a date range) but keep getting error 91 "object variable or with block variable not set" with this line of code:
vRange = Range("I" & sRow & ":" & "I" & Row).SpecialCells(xlCellTypeVisible)
I am not entirely sure why this throws an error because this works
visibleSum = Application.WorksheetFunction.Sum(Range("I" & sRow & ":" & "I" & dRow).SpecialCells(xlCellTypeVisible))
I am trying to get this block of code to return the sum of range "I, start date" to "I, end date" only counting positive numbers.
ActiveSheet.ListObjects("Table_Query_from_TCM95").Range.AutoFilter Field:=6, Criteria1:="10"
vRange = Range("I" & sRow & ":" & "I" & dRow).SpecialCells(xlCellTypeVisible)
visibleSum = Application.WorksheetFunction.Sum(vRange, ">0")
MsgBox (visibleSum)
EDIT - Thanks for the comments! both helped :D
Ultimately this counts hours each department worked where each department has its own number. 10, 20, etc. When I define my range for department 95, for the first week there are no cells which throws error 1004. That happens when the visible cells do not contain data for the date range specified. I attempted a couple different if statements this being one:
If Range("I" & sRow & ":" & "I" & dRow).SpecialCells(xlCellTypeVisible) Is Nothing Then
Else
Set vRange = Range("I" & sRow & ":" & "I" & dRow).SpecialCells(xlCellTypeVisible)
visibleSum = Application.WorksheetFunction.Subtotal(9, vRange)
MsgBox (visibleSum)
End If
Specifically this line
Set vRange = Range("I" & sRow & ":" & "I" & dRow).SpecialCells(xlCellTypeVisible)
gives error 1004 no cells found
I have 8 different Criteria that I have to iterate through. I am thinking about a select case but not sure if that will be efficient or actually accomplish what I need.
Any thoughts or tips are greatly appreciated!!
Thanks in advance!!

dynamic reference in VBA Index function

I would like to dynamically apply below INDEX function for two ranges where one range should be dependent on an iterator i.
Could anyone help how to write that down instead of my code example (only the Index part with the reference, please)?
With ActiveSheet
For i = 1 to 5
.Range("c" & i & ":I" & i & "") = [INDEX(EURbased!C5:I5 * EURbased!C4:I4,0)]
Next
End With
I would like to use iterator i instead of the "5" in EURbased!C5:I5
Try it like this:
With ActiveSheet
For i = 1 to 5
.Range("c" & i & ":I" & i & "").formula = "=INDEX(EURbased!C" & i & ":I" & i & " * EURbased!C4:I4,0)"
Next
End With
I have not tried it myself, but as far as you mentioned I would like to use iterator i instead of the "5" in EURbased!C5:I5 I think it should work.

Filling cells with loop in VBA Excel [duplicate]

This question already has an answer here:
Using VBA to place multiple formulas in one cell
(1 answer)
Closed 6 years ago.
I'm trying to fill cells with a for loop like this:
For i = 1 To Target
Range("C" & i & ":C" & i ).Formula = "='Sheet1'!A" & i & "/" & "'Sheet2'!B" & i"
Next i
And I want to see that in the formula bar:
='Sheet1'!A1 & "/" & 'Sheet2'!B1
='Sheet1'!A2 & "/" & 'Sheet2'!B2
...
Unfortunately it's not working. If I try only the first part like that:
For i = 1 To Target
Range("C" & i & ":C" & i ).Formula = "='Sheet1'!A" & i
Next i
This code results this fine, but this is not enough for me:
='Sheet1'!A1
='Sheet1'!B1
...
What is wrong with my frist code?
You could try
Range("C" & i & ":C" & i).FormulaR1C1 = "=Sheet1!RC1 & ""/"" & Sheet2!RC2"
If you are having trouble with double quotes in a concatenated string, I sugest you remove as many as you can. Single characters can be referred to by their ASCII code number with the Chr function. The / character is 47.
Dim i As Long, target As Long
With ActiveSheet
target = .Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To target
.Range("C" & i).Formula = "='Sheet1'!A" & i & Chr(47) & "'Sheet2'!B" & i
Next i
End With
You do not have to increment through a range is the formula is constructed properly. Either an xlA1 or xlR1C1 reference style can be used (see xlReferenceStyle enumeration).
Dim i As Long, target As Long
With ActiveSheet
target = .Cells(Rows.Count, "A").End(xlUp).Row
'xlA1 style
.Range("C1:C" & target).Formula = "='Sheet1'!A1/'Sheet2'!B1"
'xlR1C1 Style
.Range("C1:C" & target).FormulaR1C1 = "='Sheet1'!RC1/'Sheet2'!RC2"
End With
Note that an xlR1C1 style requires the Range.FormulaR1C1 instead of the Range.Formula.

Correct formula giving "Run-time error '1004': Application-defined or object-defined" error when running sub

I want to paste formula's in column B with a delay in between. The formula should only paste the formula if the cell left to it (in case of B1 this is A1) is not empty, like this:
I have the following VBA that pastes the formula with a delay of 1 sec.
Option Explicit
Sub RetrieveDataDelay()
'paste formulas into cells, then calculate, then delay rinse repeat
'=========================
'Declare Variables
'=========================
Dim i As Long 'used to loop
Dim rowCount As Long
Dim LastRow As Long 'used to find the last row
'=========================
'Setup for Speed
'=========================
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'=========================
'Define Variables
'=========================
LastRow = Worksheets(ActiveSheet.Name).Cells(Rows.Count, 1).End(xlUp).Row 'This will find the last used row in column A, change the number 1 to whatever column number you want
rowCount = 1 ' set to how many rows you want to do at a time
'=========================
'Do Work
'=========================
For i = 1 To LastRow Step rowCount
Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "'=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))" 'set the formula to whatever it needs to be
Calculate
Application.Wait (Now + TimeValue("00:00:01")) 'this delays 1 second
Next i
'=========================
'Setup for Speed - Reverse
'=========================
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
The error occurs at this part
Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))"
The errors has something to due with the formula, which it does not accept. This is a custom formula used with an excel extension. I know that the formula works, as I put a single quotation mark in front as such:
Range("B" & i, "B" & WorksheetFunction.Min(i + rowCount - 1, LastRow)).Formula = "'=IF(ISBLANK(A" & i & ");" & """" & """" & ";Dump(Volumes(A" & i & ";2528;1010;TRUE;" & "Volume" & ";TRUE)))"
so that it pastes the formally literally. If I then remove the quotation mark from the formula the formula works. So the questions remains why it doesn't accept this specific formula in the VBA.
Using Excel 2013.
Range.Formula needs the formula notation always in en_us format independent of the current locale settings. That means functions in English language and also comma as delimiter between formula parameters and not semicolon.
So
.Formula = "=IF(ISBLANK(A" & i & ")," & """" & """" & ",Dump(Volumes(A" & i & ",2528,1010,TRUE," & "Volume" & ",TRUE)))"
After setting Range.Formula, the locale settings will be nevertheless active in the sheet. So in the sheet the formula will be delimited with semicolons if so set.
Btw.: The complicated string notation for double quotes is not neccessary.
.Formula = "=IF(ISBLANK(A" & i & "),"""",Dump(Volumes(A" & i & ",2528,1010,TRUE," & "Volume" & ",TRUE)))"