I'm trying to use a variable into formula using VBA. I've referenced How to pass an integer variable into a vba formula this question and tried implementing that in my if formula.
=IF (startCell >0, startcell+confirmed, endcell+confirmed)
but I'm still unsure and getting an error.
My code is the following:
headerrow = 7
startCell = 8
endCell = 3
confirmed= 5
DDSS_Actual.Cells(headerrow + 3, 3).Formula = "=IF(" & startCell & ">" & endCell & ","& startCell & "+" &confirmed&", " & endCell & "+" &confirmed &")"
Thanks.
You just need to put spaces before and after the &
which makes it
DDSS_Actual.Cells(headerrow + 3, 3).Formula = "=IF(" & startCell & ">" & endCell & "," & startCell & "+" & confirmed & "," & endCell & "+" & confirmed & ")"
Related
I'm trying to do a VBA code to accomplish 2 things as follows:
Count how many characters there is on cell A1, using the formula LEN(A1) and one the last line, I'm trying to have the formula RIGHT(LEFT(A1;Q1-2);6) on cell J1
Please follow down my VBA code so far:
LR = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To LR
cel = "A" & i
cel2 = "P" & i
cel3 = "Q" & i
Range("P" & i).Formula = "=LEN(" & cel & ")"
Range("J" & i).Formula = "=RIGHT(LEFT(" & cel & "," & cel3 & "-" & 2 & ")," & 6 & ")"
Next i
It seems something silly what is missing, however, I couldnt manage to solve it so far
Thanks in advance
You’re missing a Right, and some other things
Range("J" & i).Formula = "=RIGHT(LEFT(" & cel & "," & cel3 & "-2), 6)"
There is a particular part of my code which I cannot make work,
I'm trying to do the following command on VBA =RIGHT(LEFT(X1;Z1-2);LEN(LEFT(X1;Z1-2))-FIND(":";X1))
On cell X1, there is a text: RESULTS:NG & MODEL:IJ
My VBA code is:
LR = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To LR
cel = "A" & i
cel2 = "Y" & i
cel3 = "Z" & i
cel4 = "X" & i
Range("M" & i).Formula = "=RIGHT(LEFT(" & cel4 & "," & cel3 & "-" & 2 & "),LEN(LEFT(" & cel4 & "," & cel3 & "-" & 2 & "))-FIND(:" & cel4 & "))"
Next i
I'm open for a better approach for this issue as well
Thanks in advance
Try writing all the formulas at once and reduce using quotes within the formula as much as possible.
Range(Cells(1, "M"), cells(lr, "M")).Formula = _
"=RIGHT(LEFT(X1, Z1-2), LEN(LEFT(X1, Z1-2))-FIND(char(58), X1))"
All range and cells reference within a sub procedure are better with a properly defined parent worksheet reference.
dim lr as long
with worksheets("sheet1")
LR = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range(.Cells(1, "M"), .cells(lr, "M")).Formula = _
"=RIGHT(LEFT(X1, Z1-2), LEN(LEFT(X1, Z1-2))-FIND(char(58), X1))"
end with
I am trying to make it easier for users to work with an excel sheet instead of having to modify an arduous expression anytime a change is needed. I am dynamically placing the function's result into a cell. I got everything functioning how it should except:
If I go to another sheet and use the formula, it will return the proper results; however, when returning to another sheet that was already using using it, that sheet will display the most resent results and no longer its own instance of passed variables. These sheets also tie into a dashboard sheet so I need to make sure that if I calculate one sheet, it doesn't tamper with the others. I wasn't sure how to word this issue, so if there is nomenclature in place that I am not using or if this has been answered in the past, let me know and I will close this out.
'-------------------
'getScore
' This function is called from a cell and is passed an intager.
' The integer represents the section that it is being called from.
' There is also the sheet title that is passed thrugh to the range.
'-------------------
Function getScore(section As Integer, sheetTitle As String)
Application.Volatile
Dim rngSt As Integer
Dim rngEnd As Integer
rngSt = getRange(section, sheetTitle, 1) 'Gets start range for formula
rngEnd = getRange(section, sheetTitle, 2) 'Gets end range for formula
Dim Formula As String 'Broken into seperate concatinated lines for readablility
'-(COUNTBLANK(H" & rngSt & ":H" & rngEnd & ")),"
' This section uses nested if statements to acrue the score through each level.
Formula = "=IF(SUM(D" & rngSt & ":D" & rngEnd & ")= nonBlank(D" & rngSt & ":D" & rngEnd & "),"
Formula = Formula & "IF(SUM(F" & rngSt & ":F" & rngEnd & ")= nonBlank(F" & rngSt & ":F" & rngEnd & "),"
Formula = Formula & "IF(SUM(H" & rngSt & ":H" & rngEnd & ")= nonBlank(H" & rngSt & ":H" & rngEnd & "),"
Formula = Formula & "IF(SUM(J" & rngSt & ":J" & rngEnd & ")= nonBlank(J" & rngSt & ":J" & rngEnd & "),"
Formula = Formula & "IF(SUM(L" & rngSt & ":L" & rngEnd & ")= nonBlank(L" & rngSt & ":L" & rngEnd & "),5,4),3),2),1), 0)"
getScore = Eval(Formula) 'Evaluates formula and returns a score of 0-5.
End Function
Here is the getRange fucntion
Function getRange(section As Integer, sheetName As String, rangePoint As Integer)
Application.Volatile
Dim FindRow As Range
Dim ws As Worksheet
Dim wb As Workbook
Set wb = ActiveWorkbook
If section = 1 Then
If rangePoint = 1 Then
With wb.Sheets(sheetName)
Set FindRow = .Range("C9:C9")
End With
getRange = FindRow.Row
End If
If rangePoint = 2 Then
With wb.Sheets(sheetName)
Set FindRow = .Range("C:C").Find(What:="rngEnd", LookIn:=xlValues)
End With
getRange = FindRow.Row - 1
End If
End IF
End Function
Here is my Eval fuction
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
nonBlank fucntion
Function nonBlank(r As Range) As Long 'Counts and returns the number of non blank cells found in given range.
Application.Volatile
nonBlank = r.Cells.Count - WorksheetFunction.CountBlank(r)
End Function
In your case, the function is returning exactly what you tell it to. Your UDF has no specification of worksheet anywhere. What you see on the first sheet, after the second sheet calculates, is the returned value of the function, since it calculated on the second sheet. It's a little confusing, so let me try to break it down another way.
You enter a formula with UDF on Sheet1
UDF calculates on Sheet1, with Sheet1 ranges
You navigate to Sheet2 and recalculate UDF entered there
UDF calculates on Sheet2, with Sheet2 ranges
Concurrently on Sheet1 the UDF also calculates, with Sheet2 ranges (this is why you get the same results)
Since calculation doesn't happen when you change sheets, you still see the results calculated correctly.
Bottom line (TL;DR): Your UDF is poorly written.
To help with an answer to your question, please post your getRange function as Scott asked, as well as an example of how you are calling the UDF.
Edit: I see you posted the getRange function, but it's not complete. I think you're missing an End If statement perhaps. Also, your getScore function doesn't compile because you have an extra ">" character in there. Not sure what it's doing in there.
Formula = "=IF(SUM('" & sheetTitle & "'D" & rngSt & ":D" & rngEnd & ")= nonBlank('" & sheetTitle & "'D" & rngSt & ":D" & rngEnd & "),"
Formula = Formula & "IF(SUM('" & sheetTitle & "'F" & rngSt & ":F" & rngEnd & ")= nonBlank('" & sheetTitle & "'F" & rngSt & ":F" & rngEnd & "),"
Formula = Formula & "IF(SUM('" & sheetTitle & "'H" & rngSt & ":H" & rngEnd & ")= nonBlank('" & sheetTitle & "'H" & rngSt & ":H" & rngEnd & "),"
Formula = Formula & "IF(SUM('" & sheetTitle & "'J" & rngSt & ":J" & rngEnd & ")= nonBlank('" & sheetTitle & "'J" & rngSt & ":J" & rngEnd & "),"
Formula = Formula & "IF(SUM('" & sheetTitle & "'L" & rngSt & ":L" & rngEnd & ")= nonBlank('" & sheetTitle & "'L" & rngSt & ":L" & rngEnd & "),5,4),3),2),1), 0)"
Please note this is the quick fix. I wouldn't write a UDF this way. But we would need much more detail if we delve into that.
EDIT: If I understood what you need, this is a much shorter version and should fix the issue you're seeing...
Function Score( _
ByVal Section As Long, _
ByVal Anchor As Range _
) As Long
Dim CheckRange As Range
Application.Volatile True
Set CheckRange = Anchor.Parent.Range("C9", Anchor.Parent.Cells(Anchor.Parent.Rows.Count, "C").End(xlUp))
Score = Abs(CLng(WorksheetFunction.CountA(CheckRange.Offset(0, 1)) = CheckRange.Cells.Count) + _
CLng(WorksheetFunction.CountA(CheckRange.Offset(0, 3)) = CheckRange.Cells.Count) + _
CLng(WorksheetFunction.CountA(CheckRange.Offset(0, 5)) = CheckRange.Cells.Count) + _
CLng(WorksheetFunction.CountA(CheckRange.Offset(0, 7)) = CheckRange.Cells.Count) + _
CLng(WorksheetFunction.CountA(CheckRange.Offset(0, 9)) = CheckRange.Cells.Count))
End Function
You would then call these from any cell like this...
=Score(1,A1)
=Score(1,Sheet2!A1)
=Score(1,'Some other sheet'!A1)
I'm not even sure what the 'Section' variable is for. There isn't much explanation here.
Thanks, Zack Barresse
I have a piece of code that loops down a column and inserts a formula into each cell in that column. The code runs, the only problems is that each cell the formula is inserted into displays #Value! Does anyone know how to fix this?
Here is the piece of code with the problem:
Dim j As Long
'Loop down the rows in mainfile
For j = 2 To lastFullRow2
' Make each argument a string, then concatenate it all all into large string
Dim firstArgument As String
firstArgument = "ws_multidax.Range(" & valuecolumnLetter & "2:" & valuecolumnLetter & lastFullRow1 & ")"
Dim secondArgument As String
secondArgument = "ws_multidax.Range(" & parameter1columnLetter & "2:" & parameter1columnLetter & lastFullRow1 & ")"
Dim thirdArgument As String
thirdArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim fourthArgument As String
fourthArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim condition3 As String
condition3 = "ws_mainfile.Range(" & "D2:" & D & j & ")"
Dim patid1 As String
patid1 = "ws_multidax.Range(" & "D2:" & D & lastFullRow2 & ")"
With ws_mainfile
Dim commandstring As String
'The formula we want is a concatenated string
commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'ws_mainfile.Range("AN" & j).Formula = commandstring
End With
Next j
The #Value! gets put into the cells when I run the line with the Eval(commandstring). When I run the line with just formula = commandstring, the formula gets put in each cell, but it does not solve.
Your code has 2 problems:
You are putting in the curly braces of an array formula manually, don't do this
You are putting in an array formula as a regular formula
So to correct, do the following:
'1. Change this line:
commandstring = "{=INDEX(....)}"
'And simply remove the curly braces {} from its beginning and end
commandstring = "=INDEX(....)"
'2. Change this line:
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'To use the .FormulaArray property instead of just .Formula:
ws_mainfile.Range("AN" & j).FormulaArray = commandstring
You're on the right track. There's no need to use the eval function, as you have built a string formula in code. The problem is you have surrounded it with the braces, which excel treats as if you had entered text.
Try this instead:
commandstring = "=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = commandstring
I have used the below code to get the answer. I m getting the result at my required location but sum is not displayed.
Cells(lastrow, 2).Offset(3, 1).Value = "=Sumif(L4:L" & lastrow & "," & "NEW ALBERTSONS INC" & ",J4:J" & lastrow - 1 & ")"
Could some one help me how to sort it out.
Try this one:
Cells(lastrow, 2).Offset(3, 1).Formula = "=SUMIF(L4:L" & lastrow & "," & """NEW ALBERTSONS INC""" & ",J4:J" & lastrow & ")"
Some notes:
I'm using """NEW ALBERTSONS INC""" instead "NEW ALBERTSONS INC"
(you should escape your quotes when constucting excel formulas
through vba)
sum_range and criteria_range should have same dimmentsion, that's
why you should use L4:L" & lastrow and J4:J" & lastrow (or &
lastrow-1 for both ranges)
actually, you can slightly simplify your formula by changing "," & """NEW ALBERTSONS INC""" to ", ""NEW ALBERTSONS INC"""