Is there a way to execute VBA code contained in a cell? - vba

I'm building a macro in Excelto run rules against a set of data and output whether each row passes or fails the rules. I want to be able to add, remove, or alter the rules without altering the macro. As such I have a DATA worksheet and a RULES worksheet and the macro generates the OUTPUT worksheet and then populates it.
RULES is set up so that each different rule is enumerated on a different row. For this to work I need to be able to enter the actual VBA code relevant to the rule in on RULES, then I need to have the macro look at that column on RULES and execute the code in the cell.
Simplified example of my setup-
DATA has : ID, Dividend1, Dividend2, Divisor. There are n rows on DATA.
An example of a row on DATA might be ID="123", Dividend1=5, Dividend2=7, Divisor=35.
RULES has : Name, Formula, Threshold. For simplicity's sake there is only .
Let's set the as Name="Example", Formula=[see below], Threshold="0.15" (Threshold is used for conditional formatting in the macro, in this example it is unused.)
I'm going to use pseudocode for Formula just to eliminate the need to explain some of the irrelevant particulars of my macro so far. RULES.Formula should contain a line of VBA code that carries out-
If CurrentDATARow.Dividend1 = Empty Then
CurrentDATARow.Dividend2 / CurrentDATARow.Divisor
Else
CurrentDATARow.Dividend1 / CurrentDATARow.Divisor
End If
So, all of this explanation just to give context to this question: What can I do in the VBA of the macro to make it read the contents of RULES.Formula and make it execute that code inline with the rest of the macro?

If you have (say)
IF({dividend1}="",{dividend2}/{divisor},{dividend1}/{divisor})
stored in a "rule" cell (note do not include the "="), you can use Replace() to replace the placeholders with the relevant cell addresses for each cell in the row you're checking.
Then use something like
Dim val
val=Sheet1.Evaluate(yourformulastring) 'evaluate vs. specific worksheet
If Not IsError(val) Then
'check against thresholds etc
End If
If the evaluation results in an error you can test with IsError(val) as shown, otherwise it will return the result of the formula, which you can test against your "threshold" value cell. If you set background colors on your threshold cells you can color each row according to which threshold was exceeded.
NOTE without a worksheet qualifier, Evaluate will calculate the formula based on the ActiveSheet, so make sure the right sheet is active when this runs if you don't use the qualifier.

you could store your Tests/Rules as Excel worksheet formulas in Named ranges. Then you just call them from the cells.
see Ozgrid: Named Formulas
If you give us some example data and the type of calculations or rules I can give you a couple of examples.

Related

SUMIFS returns 0 using dynamic criteria, with criteria range and sum range on another sheet

Anyone,
I've chatted with and called excel customer service with no luck. I used the formula builder (please see attached screenshot) to make sure each element of the formula is correct and returns the value for the criteria I'm trying to reference.
Everything is accurate, but it returns a value of 0. When I do the same thing in the actual sheet the data is stored in (and click a criteria cell within the criteria range) it returns the accurate value?! I'm not sure why it won't work on the other sheet. The values I am using to select are dynamic and change with a drop down. I have another, advanced, workbook (I did not create) that does the same thing and completes an even more complicated formula, but actually works so I'm not sure why this is returning a 0 value.
Photos and code/syntax: Dynamic Selection, Example 2 of it working, Example 1 of it working, Formula Builder, CountIFs, Advanced Spreadsheet working, VLOOKUP
=SUMIFS('GFEBS Pull'!Q:Q,'GFEBS Pull'!G:G,FMCOP!$C$20,'GFEBS Pull'!H:H,FMCOP!B23)
or:
=SUMIFS('GFEBS Pull'!Q:Q,'GFEBS Pull'!G:G,'FMCOP'!$C$20,'GFEBS Pull'!H:H,'FMCOP'!B23)
When I type ' around FMCOP sheet name, they disappear? I've also tried to lock the columns on the 'GFEBS Pull' sheet with no luck. Cell B23 is not locked because I'm going to copy the formula down to reference other cells. Any help is appreciated!
In this screenshot you can clearly see that both FMCOP!C20 ansd FMCOP!B23 have prefacing spaces; e.g. " HHC".
Since " HHC" will never match "HHC", fix the data returned from 'the lower table in the same screenshot'.
A Text-to-Columns, Fixed Width, Finish should do this. You could adjust the original formula like,
=SUMIFS('GFEBS Pull'!Q:Q, 'GFEBS Pull'!G:G, TRIM(FMCOP!$C$20), 'GFEBS Pull'!H:H, TRIM(FMCOP!B23))
I would caution against the latter 'bandaid' fix. Fix the original data; do not apply bandaids on-the-fly.

percentile formula error in VBA

I'm trying to apply a formula through VBA for a particular range. This is the code in my VBA editor:
Sheets("WBR45").Range("AE105").Formula = "=PERCENTILE.INC(TP!$A$3:$A$30:$B$3:$B$30:$C$3:$C$30:$E$3:$E$30,50%)*24"
And the below formula gets updated in the destination cell when this is run:
=PERCENTILE.INC(TP!$A$3:$A$30:$B$3:$B$30:$C$3:$C$30:$E$3:$E$30,50%)*24
But I get an error in the destination cell as #VALUE!.
And when I click on "Show Calculation steps", only this part of the formula is underlined :
TP!$A$3:$A$30:$B$3:$B$30
I have no idea what is wrong with this simple formula. Can someone please take a look
Honestly I have no clue about what you're doing with this, but this may fix it:
"=PERCENTILE.INC(TP!$A$3:$A$30:TP!$B$3:$B$30:TP!$C$3:$C$30:TP!$E$3:$E$30,50%)*24"
You appear to have three errors in your formula:
You are using : to separate ranges instead of ,
You are not specifying which sheet the second, third and fourth ranges refer to, therefore it is defaulting to the sheet on which the formula occurs (i.e. sheet "WBR45")
Multiple ranges will need to be enclosed within brackets (...) in order to be passed as a single range.
If you are trying to have your function operate on the range A3:C30 together with the range E3:E30 (i.e. A3:E30 but ignoring column D), with those ranges being on the "TP" worksheet, I believe that you need to change your formula to
Sheets("WBR45").Range("AE105").Formula = "=PERCENTILE.INC((TP!$A$3:$A$30,TP!$B$3:$B$30,TP!$C$3:$C$30,TP!$E$3:$E$30),50%)*24"
or, slightly simplified
Sheets("WBR45").Range("AE105").Formula = "=PERCENTILE.INC((TP!$A$3:$C$30,TP!$E$3:$E$30),50%)*24"

Convert Excel Formula to 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.

Return blank if #VALUE is returned

I've setup a formula that combines numbers from multiple worksheets and then compares it against another number from worksheet.
I am using the INDIRECT function to reference the sheets as well as COLUMN and ROW to adjust the numbers to the corresponding coordinates when I drag it across.
However, some of the figures don't always exist in the worksheets so a #VALUE error is returned. How Can I change it so a blank cell is shown if this happens?
My Current formula: =INDIRECT("'"&$C$11&"'!R"&ROW(E29)&"C"&COLUMN(E29),FALSE)-SUM(INDIRECT("'"&$C$11&"'!R"&ROW(C29)&"C"&COLUMN(C29),FALSE),INDIRECT("'"&$C$13&"'!R"&ROW(E29)&"C"&COLUMN(E29),FALSE))
Use =IFERROR(<your original formula>, "") which will replace any error with "" but passes any other result through.
But do bear in mind the degradation in spreadsheet stability: INDIRECT makes spreadsheets brittle enough on its own: your hiding any error output could be dangerous.

MS Excel dynamic print area

I wish to create a dynamic Print_Area in Excel 2010 which will consist of two cell ranges.
For example the first cell range is A1:J50 and the second range is A100:J150. These should print out on two pages, ignoring the cells that come in between these two ranges.
The four cells shown in the above example ranges should be dynamic, and not hard coded as simple Print_Area ranges. Therefore in my worksheet I used cells AA1, AB1, AC1 and AD1 to store values "A1", "J50", "A100" and "J150" respectively.
(The cells AA1, AB1, AC1 and AD1 actually use formulas to determine what cell address will be used, but for this question lets just assume the values are set as above).
I then used the Name Manager and entered the following formula under Print_Area:
=INDIRECT(Sheet1!$AA$1):INDIRECT(Sheet1!$AB$1);INDIRECT(Sheet1!$AC$1):INDIRECT(Sheet1!$AD$1)
The result of this formula is exactly what I need, and it actually works the first time I print the ranges. However once I did that, Excel automatically substitutes the formula with the actual cell range that was calculated. So when I check the Print_Area in the Name Manager after printing once, it contains something like:
=Sheet1!$A$1:$J$50,Sheet1!$A$100:$J$150
Is there a way to prevent the Print_Area from converting my formula to calculated values, and instead using the formula every time I print? I would like to not use macros if at all possible (if not, I'll try macros too)
I tested this and it seemed to work.
Create a new name called Test and set its value to (Note that I used a comma rather than the semicolon you had. I have US language set)
=INDIRECT(Sheet1!$AA$1):INDIRECT(Sheet1!$AA$2),INDIRECT(Sheet1!$AA$3):INDIRECT(Sheet1!$AA$4)
Set your Print_Area name to
=TEST
Good luck!
EDIT
The above works for me, but it appears unnecessary. I just tried to replicate the problem, and was unable. When I have the Print_Area set to the formula with INDIRECT it does not replace after printing.
See this linked file. https://www.dropbox.com/s/pgm0iv19u6igdm5/Book1.xlsx