dynamic reference in VBA Index function - vba

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.

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

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

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.

VBA Offset within Vlookup?

I'm trying to get a Vlookup for a row which is just left of the Lookup_value. I can't do a Table_array of "-1" (or -2) so I'm wondering if I can do an Offset(0, -1) within that line of code.
The line in question:
wCell.FormulaR1C1 = "=VLOOKUP(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5,-1,FALSE)"
The entire code block:
Range("$C$8:$C$" & lastrow).Select
For Each wCell In Range("$C$8:$C$" & lastrow)
wCell.Select
If wCell.FormulaR1C1 = "" Then
wCell.FormulaR1C1 = "=VLOOKUP(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5,-1,FALSE)"
End If
Next
If you were looking to find information to the left of the reference point in excel, using a Match-Index lookup would be they way for you to go. Not only is this method able to look to the left or right of your reference, but it is also a faster process.
VLookup looks like this:
=VLookup([Value to find],[Where to find the value],[Column to return],[range lookup])
Where as using Match-Index looks like this:
=Index([Range to look in for return],Match([Value to find],[Range to look in for value],[Exact match or partial]))
So, while a bit more complicated to write, using the second method really increases the flexibility of what you can look up and where that information is.
Now, if you were to apply this method to your code, it should look something like this:
wCell.FormulaR1C1 = "=Index([Range of Value to Find],Match(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5, [0 for exact match]))"
(Just change out the bits I added in brackets for the information that they need, and that should address that problem your are running into)

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