VBA -- variable in .formula - vba

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 :)

Related

Concatenate two ranges without looping

I want to concatenate two ranges into one WIHTOUT using a loop.
Below is the code. The lines with comment's is basically the solution I want to avoid.
With ws_AUoM
lCountEntriesInAUoMFile = .Cells(Rows.Count, "B").End(xlUp).Row
.Range("O2:O" & lCountEntriesInAUoMFile).Value = .Range("B2:B" & lCountEntriesInAUoMFile).Value & .Range("F2:F" & lCountEntriesInAUoMFile).Value
' For lLoopCounterAUoM = 2 To lCountEntriesInAUoMFile
'
' .Cells(lLoopCounterAUoM, "O").Value = .Cells(lLoopCounterAUoM, "B").Value & .Cells(lLoopCounterAUoM, "F").Value
'
' Next lLoopCounterAUoM
End With
This line:
.Range("O2:O" & lCountEntriesInAUoMFile).Value = .Range("B2:B" & lCountEntriesInAUoMFile).Value & .Range("F2:F" & lCountEntriesInAUoMFile).Value
returns the error "Type Mismatch". I have double checked the sizes and location of each range. Yet it does not work. What am I missing here?
You can do this:
Dim r As Long
With ws_AUoM
r = .Cells(.Rows.Count, "B").End(xlUp).Row
.Range("O2:O" & r).Value = .Evaluate("B2:B" & r & " & F2:F" & r)
End With
Evaluate knows you're giving it an array formula, and will return the resulting array, which you can assign directly to the sheet.

VBA Run-time Error 1004 for Special Characters in Soft-coded Vlookup Function

When I was trying to throw a vertical bar "|" into my vlookup function, I got a 1004 error. I am not sure where it came from.
Initially the data table looks like this:
And my code was like this:
Sheets("Sheet 1").Cells(i, 2).Formula = "=VLOOKUP($A" & i & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"
Everything worked fine till the format of the data table got changed to:
So I had to throw the vertical bar "|" into my code. My new code was like this:
NewKey = Sheets("Sheet 1").Cells(i, 1).Value & "|" & Sheets("Data").Cells(i, 2).Value
Sheets("Sheet 1").Cells(i, 3).Formula = "=VLOOKUP(" & NewKey & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"
Apparently Excel 2010 did not like my codes and threw me a 1004 error. I am wondering if anyone knows a solution to this. Thank you in advance for your help.
NewKey needs to be in quotes when the formula is placed on the sheet, so you need to include the quotes in the string:
NewKey = Sheets("Sheet1").Cells(i, 1).Value & "|" & Sheets("Sheet1").Cells(i, 2).Value
Sheets("Sheet1").Cells(i, 3).Formula = "=VLOOKUP(""" & NewKey & """,Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"

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.

Looping through cells, building a range in 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