Convert Excel Formula to VBA - vba

I have this formula that looks at various criteria across multiple columns and checks to see that if all the all the criteria match, it will paste data from one column to another. I've tried a couple ways to get it into VBA, but I can't seem to get anything to work. Thanks!
=INDEX($D$2:$D$1112,MATCH(1,($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3),0))

You are not going to be able to use that array formula to directly return a value to a cell. VBA does not process an array formula the way that the worksheet can. The best method is to use the worksheet's processing or one of the Application Evaluate methods.
Your lack of a worksheet to reference troubles me. When a formula is in a worksheet cell, it knows what worksheet it is on. When using formulas within VBA, the parent worksheet is a 'best guess' without explicit worksheet referencing.
Here are three methods to put the results from that array formula into Z2:Z4 on the active worksheet. Remember that these cell references should be modified to include the worksheet name.
With ActiveSheet
'this simply puts the formula into the worksheet then reverts the cell from the formula to the returned formula value
.Range("Z2").FormulaArray = "=INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))"
.Range("Z2") = .Range("Z2").Value
'this uses the 'square bracket' method of evaluating a formula on-the-fly
'the formula being evaluated can be array or non-array
'this method is does not like building a formula string from pieces of text
.Range("Z3") = [INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))]
'similar to the method directly above, Application.Evaluate does just that.
'the formula being evaluated can be array or non-array
'this method is easier to build a formula string from pieces of text
.Range("Z4") = Application.Evaluate("INDEX($D$2:$D$1112, MATCH(1, ($A$2:$A$1112=$U$7)*($C$2:$C$1112=$W$7)*($B$2:$B$1112=F3), 0))")
End With

You need 2 changes:
(1) To use a function in VBA when it is available in native Excel, you need to preface each function with Application.WorksheetFunction. ie:
x = Application.WorksheetFunction.Sum(y,z)
(2) To reference a cell within a sheet, in VBA, you need to access it specifically, in one of a few ways. The simplest for our purposes is the RANGE property, as follows:
x = Application.WorksheetFunction.Sum(Range("A1:A2"))
So to put those two changes together, your formula would look like this:
=Application.WorksheetFunction.INDEX(Range("$D$2:$D$1112",Application.WorksheetFunction.MATCH(1,(RANGE("$A$2:$A$1112"=RANGE("$U$7")*(Range("$C$2:$C$1112"=Range("$W$7")*(Range("$B$2:$B$1112"=Range("F3"),0))
Although I see now having gone through this that you seem to be using an Array Formula - not sure if any special jigging is required to get that to work.

Related

VBA Worksheets.Calculate not working with Evaluate referring to expression on another sheet

I am intrigued by the VBA statement Worksheets.Calculate. It appears to me that it does not work correctly with custom function using Evaluate Statement when the function refers to cells on another sheet within the same workbook.
On Sheet1 I have Column A with just plain numbers.
Sheet2 in same workbook Column C has basic expressions on Column A Cells like A1+A2 etc.
I have this custom function in VBA Module
Function MyEval(Val1 As String)
Application.Volatile
MyEval = Evaluate(Val1)
End Function
And I put this formula =MyEval(Sheet2!C1) in say B1 in Sheet1 and drag it down.
This works fine for the first time. It takes in Expression in Sheet2:C1 passes it to MyVal, inside evaluates and returns the result.
The issue is the moment I edit the string expression in Sheet2, this entire formula returns 0. I need to Press F9 on Sheet1 to recalculate.
I have put Application.Volatile in MyVal and Worksheets("Sheet1").Calculate in Worksheet Change event in Sheet2.
Still it does not work. The only way to make it work is Press F9 on Sheet1.
Is this expected behavior? Am I missing something. How to I make a custom formula in VBA using Evaluate statement recalculate when there’s worksheet change event and the formula refers to range on another sheet?
No issue if the reference is in the same sheet. It works fine though. I have Excel 2013. Thanks.
Screenshot
The problem is that your code is calling Application.Evaluate which works in the context of the active sheet. If you want it to evaluate in the context of the sheet the function is on, you should use the worksheet.evaluate method like this:
Function MyEval(Val1 As String)
Application.Volatile
MyEval = Application.Caller.Worksheet.Evaluate(Val1)
End Function

Excel formula within VBA

I have quite a few cells that contain formula, then with VBA the outcome of this formula is the value for a variable, like so:
On sheet in cell AS4:
=SUMPRODUCT(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
and then in my VBA:
numRows = ws.Range("AS4").Value
However this is starting to get hard to keep track of which cell is feeding which variable, avoiding overwriting those cells on the sheet by accident, etc.
I need to be able to perform this calculation within VBA if I can, removing the need to have "calculation cells" on my sheet.
I have discovered there is a way to use formula with WorksheetFunction, but only found simple examples of this and cannot adapt it to my situation above.
numRows = WorksheetFunction.SumProduct(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
Is not going to work...
Is there a way to do this, or am I better scrapping the idea of using formula and using a pure VBA method?
With help from SJR this was the answer:
numRows = [=SUMPRODUCT(MAX((ROW(Weights!$AE$4:$AE$997))*(Weights!$AE$4:$AE$997<>"""")))]
A bit more research taught me that evaluate(" ") can be just replaced with square brackets [ and ]. Although, if I had variables in the mix of this formula or the formula wasn't constant then I would have to use Evaluate.
I also needed to add the sheet name to the formula as this formula was no longer functioning within the sheet and AE4:AE997 was no longer referring to the correct sheet.
Doubling up on quotes is also necessary as it is code and sees " differently to a formula on the sheet

SpecialCells in Excel to return value of a formula

I wanted a quick simple way to copy cell values to another sheet using SpecialCells in Excel as opposed to looping
My VBA code is as below:
Sub copyMissingData()
Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeConstants).Copy Worksheets("Destination").Range("missing_qbc")
End Sub
My source data Z4:Z20000 has formulas that returns a value (texts/numbers/fraction etc) or blank "". I want the copy to ignore the blanks, but copy any other value returned
The VBA code above using SpecialCells(xlCellTypeConstants) doesn't work because of the formula in the source range.
My question: Is there a straightforward way I can use range.specialcells to copy my data from a worksheet to another bearing in mind that source cells contain formulas and the formulas may produce empty string cells which will need to be skipped
If you have formulas, why are you trying to select the constants?
Use this:
Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeFormulas, 23).Copy
Worksheets("Destination").Range("missing_qbc").pastespecial(xlPasteValues)
The 23 means "Numbers, Texts, Logicals and Errors".
Doing the copy and paste separately ensure blanks are skipped (if that's what you mean by "ignore").
Paste values makes sure only the values get pasted, not the formulas themselves.
Please note that if you have a formula in a cell, it is not blank. Even if the formula produces an empty string value as a result, the cell itself is not empty! In htat case, you need to do a copy-paste values in place before you do anything else - and even then Excel sometimes doesn't consider blank cells blank. If this is the case, you need to iterate (loop) through the cells, and copy them one-by-one.
The easiest way I can think of is to remove the blanks after copying all:
Set rngFrom = [Source!Z4:Z2000]
Set rngTo = [Destination!missing_qbc].Resize(rngFrom.Rows.Count, 1)
rngTo.Value = rngFrom.Value
rngTo.SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
The more complicated way is with array formula, but doesn't need VBA.

Excel VBA - Interpret "N/A" Values

I am traversing a spreadsheet which contains a column of prices, in the form of double types. I am trying to locate a missing value which is shown on the spreadsheet as "n/a", but it is not letting me interpret this as a string type.
The cell containing "n/a" seems to be an integer type; how can I read this?
If all you want to do is to check for the error value then:
Application.WorksheetFunction.IsNA(rngToCheck.Value)
where rngToCheck is the cell which you want to check for the #N/A error value
(There's a list of the worksheet functions which can be called from Excel VBA here)
You could also examine rngToCheck.Text as this will contain the string "#N/A"
If instead, you want to read the formula in the cell which generated the #N/A then rngToCheck.Formula would do that
A cell containing #N/A is retrieved by VBA as a variant containing an error code
In general its usually best to assign Excel cells to Variants because a cell can contain a number(double), logical, string or error and you cannot tell in advance what the cell wil contain.
You can prepare the spreadsheet you like to check as described below and evaluate the special cells containing the IS Functions, it is easy to check them for True or False in VBA. Alternatively, you can write your own VBA function as shown below.
There are Excel functions which check cells for special values, for example:
=ISNA(C1)
(assumed that C1 is the cell to check). This will return True if the cell is #N/A, otherwise False.
If you want to show whether a range of cells (say "C1:C17") has any cell containing #N/A or not, it might look sensible to use:
=if(ISNA(C1:C17); "There are #N/A's in one of the cells"; "")
Sadly, this is not the case, it will not work as expected. You can only evaluate a single cell.
However, you can do it indirectly using:
=if(COUNTIF(E1:E17;TRUE)>0; "There are #N/A's in one of the cells"; "")
assuming that each of the cells E1 through E17 contains the ISNA formulas for each cell to check:
=ISNA(C1)
=ISNA(C2)
...
=ISNA(C17)
You can hide column E by right-clicking on the column and selecting Hide in Excel's context menu so the user of your spreadsheet cannot see this column. They can still be accessed and evaluated, even if they are hidden.
In VBA you can pass a range object as RANGE parameter and evaluate the values individually by using a FOR loop:
Public Function checkCells(Rg As Range) As Boolean
Dim result As Boolean
result = False
For Each r In Rg
If Application.WorksheetFunction.IsNA(r) Then
result = True
Exit For
End If
Next
checkCells = result
End Function
This function uses the IsNA() function internally. It must be placed inside a module, and can then be used inside a spreadsheet like:
=checkCells(A1:E5)
It returns True, if any cell is #N/A, otherwise False. You must save the workbook as macro-enabled workbook (extension XLSM), and ensure that macros are not disabled.
Excel provides more functions like the above:
ISERROR(), ISERR(), ISBLANK(), ISEVEN(), ISODD(), ISLOGICAL(),
ISNONTEXT(), ISNUMBER(), ISREF(), ISTEXT(), ISPMT()
For example, ISERR() checks for all cell errors except #N/A and is useful to detect calculation errors.
All of these functions are described in the built in help of Excel (press F1 and then enter "IS Functions" as search text for an explanation). Some of them can be used inside VBA, some can only be used as a cell macro function.

Problem using SUM(If( Rather than SumIf(

I have written a Formula in Excel that Sums up Items in 1 Column (Text) the Column is a Dynamic Named Range (Invoice_list_Item) the Formula sets a Value (Of my Choice) based on each Item in the Range and Sums those Values, I am now using a Userform where I would like to Display that Equation rather than in the workbook itself, so my problem is that everytime I write this code in the userform it doesn't work; either throwing an error, or not displaying a value. I have tried Application.Sum, Application.Sumif, Application.Sumproduct and the main one I've been trying to make work Application.Sum(If(Range(
Any Help in correcting this Formula in to a Macro will be much appreciated.
=SUM(IF(Invoice_list_Item="1/4 Item",0.25,0)+IF(Invoice_list_Item="1/2 Item",0.5,0)+IF(Invoice_list_Item="1 Item",1,0))
You can use Application.Evaluate (this works for array formulae) to evaluate a string as if it was an Excel formula:
Dim vResult As Variant
vResult = Application.Evaluate("=SUM(IF(Invoice_List_Item=""1/4 Item"",0.25,0)+IF(Invoice_List_Item=""1/2 Item"",0.5,0)+IF(Invoice_List_Item=""1 Item"",1,0))")