Using countif function with dynamic criteria - vba

Dear Madams and Sirs,
In my code I make use of an CountIf statement.
Cells(5, 3).Value = Application.WorksheetFunction.CountIf(CR, ">" & yel)
Where:
Dim yel As Double
yel = Cells(2, 5).Value
and:
Dim CR As Range
Set CR = Range("D9:Z26")
The weird thing is: If I use the dynamic criterion (& yel) the code give me a zero as result. And when I use a fixed criterion (">0") the code produces the correct number.
Can anyone tell me what I am doing wrong?
Best regards and thanks in advance,
Wouter

I venture to bet on this guess:
You are not using an English Excel. Your Excel version uses , as decimal mark.
The conversion of yel to a string leaves it with a , but the internal engine only understands the English ..
Try if this works:
Dim strYel As String
strYel = Replace(CStr(yel), ",", ".")
Cells(5, 3).Value = Application.WorksheetFunction.CountIf(CR, ">" & strYel)

Related

Writing a formula with concatenated parts into a cell

Scenario: I have a code that should write a formula to a worksheet cells. This formula is for an API to retrieve some value. My formula is inside a loop (this is done for multiple columns) and references the first row for an identifier.
The original formula:
=FS(B1;"FI(DATE,,DATE)")
The modified formula with the floating reference (inside the loop):
For i = 1 To lColumn
If wb.Worksheets("Dates").Cells(i, 1).Value <> "" Then
wb.Worksheets("Dates").Cells(i,2).value = "=FS(" & i & "1;"FI(DATE,,DATE)")"
End If
Next i
Where lColumn is some pre-defined number.
Issue: I keep getting the "Unexpected end of statement" error in the formula part of the loop.
What I already tried: I tried different variations, repositioning the "s and 's, for example:
wb.Worksheets("Dates").Cells(i,2).value = "'"=FS(" & i & "1;"FI(DATE,,DATE)")""
or
wb.Worksheets("Dates").Cells(i,2).value = "'=FS(" & i & "1;"FI(DATE,,DATE)")"
or
wb.Worksheets("Dates").Cells(i,2).value = "'""=FS(" & i & "1;"FI(DATE,,DATE)")"
and so on. But the error still persists.
Question: What is the proper way to do this operation?
Working with formulas in VBA is a little bit tricky:
To write a formula, use the range.formula property, not the .value.
You have to write the formula as if you are using an english Excel. Parameter-separator is comma (not semicolon).
If a formula needs a quote, double it so that the VBA compiler understands that you want a quote within a string.
I find it helpfull to write a formula into a variable before assigning it - you can check in the debugger if it is exactly how it should before assigning it.
To check how the formula should look like, write it into a cell, change to the VBA-editor, open the immediate window and write ? activecell.formula
Try (untested as the formula you need is not valid to us):
with wb.Worksheets("Dates")
dim f as string, adr as string
adr = cells(i, 1).address(false, false) ' get rid of Dollar signs
f = "=FS(" & adr & ",""FI(DATE,,DATE)"")"
.Cells(i, 2).formula = f
end with
wb.Worksheets("Dates").Cells(i,2).formula = "=FS(" & Cells(1, i).Address(0,0) & ";""FI(DATE,,DATE)"")"
There may be a better way to convert the column number to a letter (which is the problem you are having, along with the double quotes)!

use variable in excel formula

I'm trying to make an automated sum based on an increasing number of rows.
Here is my sample of code but I'm stuck as I don't know the syntax to include a variable in the formula of a cell.
Sheets("Orderboek").Select
Range("H" & (rOi + 1)).FormulaR1C1 = "=Sum(H3:H"&rOi&")"
My variables are declared as follows:
Dim i As Integer, a As Range 'i= index a een gebied
Dim prText As String 'product text
Dim rOi As Long 'rij nummer in orderboek
Dim rng, sumrng As Excel.Range
Dim r As Long 'rij number in offerte
Dim Tot As Long 'totaal som van offerte
Dim ws As Excel.Worksheet
Thanks very much if you can help me out.
Try this:
Range("H" & (rOi + 1)).Formula = "=Sum(H3:H" & rOi & ")"
Make sure you use .Formula and not .FormulaR1C1 in this case. Also make sure that there are spaces between ampersands.
Note that FormulaR1C1 is useful when you want to refer to a certain point and would like to enter row and cell coordinates. Since you know the column you want to work with, using Formula is better. i'll delete soon; just can't comment yet (<50rep)
*edit: so #timthebomb is spot-on. :)

VBA 1004 error : Application defined or object defined error

I am a novice at Excel VBA and am running into an error 1004 while compiling a portion of the code:
Cells(i, j).Formula = _"=vlookup(Cells(i,1).Value,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(Cells(1,j).Value,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"
i and j have been defined previously as integers and are part of a for loop. Could anyone please help me out on this?
A few things wrong there:
First, you're using the literal text "Cells(i, 1).Value" and "Cells(1, j).Value" in the formula string. You would need to concatenate the values into the string like this:
Cells(i, j).FormulaR1C1 = "=vlookup(" & Cells(i,1).Value & ",SKULifeCycle_Table_Temp!R1C1:R5000C500,match(" & Cells(1,j).Value & ",'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"
Second, you used the .Formula property but passed R1C1 style references, so you should use the .FormulaR1C1 property (as I did above).
Third, if the values in the cells that you are using for the lookup values are text, you need to enclose them in quotes:
Cells(i, j).FormulaR1C1 = "=vlookup(""" & Cells(i,1).Value & """,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(""" & Cells(1,j).Value & """,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"
or use the addresses (in R1C1 format) instead:
Cells(i, j).FormulaR1C1 = "=vlookup(RC1,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(R1C,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"
One issue that is clear (maybe the cause of the whole error), is that variables are being used within a string. So, what does that mean? I'll simplify using the code below as a template:
Sub Test1()
Dim i as Integer
Dim j as Integer
i = 2
j = 3
Cells(i, j).Value = "The row number is i and the column number is j"
End Sub
In the Cells line, it correctly refers to cell C2, which is the second row and third column. But what value is inserted into the cell? It's literally "The row number is i and the column number is j" using the letters, and not their corresponding numbers. Similarly, in your case, the formula will read: VLOOKUP(CELLS(i,1)... using the letter i, which is incorrect.
Additionally, a cell's formula doesn't use the CELLS syntax. You instead need to build a string using the variables. It would look a lot like:
"=VLOOKUP(" & Cells(i, 1).Address & "SKULifeCycle_Table_Temp!R1C1:R5000C500, Match(" & Cells(i, 1)Address ... "
Try to build out your formula string and refer back to this post with any specific questions.

Convert Excel array formula VBA

I'm trying to do "vlookup" with 2 different criteria(Column A and G values) using "Index" and "Match" functions.
and here is the line i used for the Excel command.
=INDEX(Database!A:KG,MATCH(1,(Database!A:A='TempSheet'!A2)*(Database!G:G='TempSheet'!G2),0),10)
How would I do it with VBA? It's keep giving me the error message "Compile error: Expected end of statement".
Selection= _
"=Index(DB.Range("A:KG"), Match(1, (DB.Range("A" = Temp.Range("A" & i).Value)) * (DB.Range("G" = Temp.Range("G" & i).Value)), 0), 10)"
Thanks
Every time you use a spreadsheet formula inside a VBA code, you need to precede it with <Excel.WorksheetFunction.> or <Application.WorksheetFunction.>.
For example:
Application.WorksheetFunction.Match
instead of Match only.
I have had little luck getting array formulas to work correctly via VBA, and use the 'IFERROR' as a workaround like so:
=IFERROR(VLOOKUP(A1, Database!A:Z,1,FALSE),VLOOKUP(B1, Database!A:Z,1,FALSE))
This function will attempt to match A1, and in case of a #VALUE error, it will match B1.
To get this kind of formula populated on a sheet in VBA, you can loop down your sheet using the '.formula' approach.
' get length of source data
Dim RowCount As Long
RowCount = ThisWorkbook.Sheets("Database").Cells(Rows.Count, 1).End(xlUp).Row
' now starting from row 2 to preserve headings
For i = 2 To RowCount
ThisWorkbook.Sheets("Summary").Cells(i, 1).Formula = "=IF(ISERROR(SEARCH(""ISO"",V" & i & ")),""Order type not supported"",""Transit"")"
ThisWorkbook.Sheets("Summary").Cells(i, 6).Formula = "=IFERROR(TEXT(VLOOKUP(B" & i & ",Database!A:N,7,FALSE),""dd-mmm-yyyy HH:MM AM/PM""),"""")"
Next
Not exactly what you were after, but hope it helps!

VBA/excel-VBA - add two values with dot separator

I'm new to VBA and need to add two values using VBA in Excel. I receive imported values with dot-separator and if I try to add them, the dot is ignored.
So:
1.12
1.34
should result in 2.46, but I'm getting 246
Code:
Do Until (Cells(iRow, 1) = 100)
addValue = Cells(iRow, 2).Value
dValue = dValue + addValue
iRow = iRow + 1
MsgBox (dValue)
Loop
Thanks for some 101-tips...
Here is the updated code:
Dim iRow As Integer
Dim addValue As Double
Dim dValue As Double
iRow = 2
Do Until (Cells(iRow, 1) = 100)
addValue = Cells(iRow, 8)
Debug.Print "Row"; iRow; " is "; addValue
modValue = Replace(addValue, ".", ",")
MsgBox (addValue)
newVal = Cells(iRow, 8).Value
dValue = dValue + newVal
iRow = iRow + 1
Loop
MsgBox (dValue)
Basically I have a lit of values like this:
100 header
200 1.12
200 1.34
200 1.54
100 header
...
I want to sum the 200 correspondig values 1.12, 1.34, 1.54. The values show up as 112, 134 and 154.
Thanks
Would you place this line after addValue =, please?
Debug.Print "Row"; iRow; " is "; addValue
Offhand, I am suspecting that the 1.12 is not really a double.
Also, did you declare your variables? Nothing fancy, but something like
Dim iRow As Integer
Dim addValue As Double
Dim dValue As Double
Finally, you may want to consider placing the MsgBox after the loop, instead of having it give a subtotal on every; iteration.
I think you have some funny number formatting applied to the values in Excel. Highlight the range and hit Ctrl-Shift-` (or format the cells as "General" from the format menu). I bet those numbers are actually 112 and 134.
Right... The problem is formatting, and Excel's insistence on describing (say) '4/7' as 'Fourth of July' rather than four-sevenths*. Or indeed, as a textual 'Four-slash-seven'.
I do not know what strange format has been picked up in those 'decimal' cells, but you have two jobs to do:
Change the number format of those cells to 'general' so you can see
what's actually in them, rather than whatever Excel wants to
present;
Change your code to use the 'Value2' property of a range, which
gives you the raw data instead of a formatted interpretation of the
'value' - newVal = Cells(iRow, 8).Value2
I would also recommend that you declare NewVal as Double. This will coerce a type conversion to floating-point number, a far better idea than letting a 'variant' decide what type it would like to be, based on formatting information in a range.
I'd better warn you that task (1) works about half the time on data imported from Oracle databases, and numbers copied from spreadsheets originating France (where the comma is used as a decimal point) are better-suited to the semiotic analyses developed by French Deconstructivist philosophers, rather than statistical analysis and arithmetic calculation.
*You'll be able (or unable) to reproduce this error some of the time, depending on your machine locale. And that's today's big lesson: a problem is worsened when it is intermittent, unpredictable, or inconsistently-reproducible.