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.
Related
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
I'm trying to build a small macro that allows the user to format multiple different documents at once.
I would like for the user to be able to enter into a particular cell within the document containing the macro a particular piece of text.
I then want for this piece of text to be able to be drawn upon in the macro while affecting a different document.
For instance, a code to add another column might say
Worksheets(1).Range("A1").EntireColumn.Insert
Instead of specifying the column (A), I would like it to draw on a value in the host document. For instance, the user types "G" into the particular cell, and then clicks a button to run the macro, and the macro will dynamically know to affect column G in all excel documents it targets based off of the value in the host document.
I hope this makes sense.
Any suggestions for the sort of functions I should be looking at to make this work?
"Any suggestions on the sort of functions I should be looking at?"
Here's a few...
To get the value which is entered...
If the cell will always be in the same address, say A1:
' Define a string variable and set it equal to value in A1
Dim cellText as String
cellText = ThisWorkbook.ActiveSheet.Range("A1").Value
or instead of using Range you can also use Cells which takes a row and column number.
cellText = ThisWorkbook.ActiveSheet.Cells(1, 1).Value
If the cell changes then you may need to look into the Find function to look for a label/heading next to the input cell. Then you can use it (easily with Cells) to reference the input...
Once you have this variable, you can do what you like with it.
To put this value into cell B3 in another (open) workbook named "MyWorkbook", and a sheet named "MySheet" you can do:
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range("B3").Value = cellText
To insert a column at cellText, do
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range(cellText & "1").EntireColumn.Insert
Notably here, the & concatonates the strings together, so if
cellText="B"
then
cellText & "1" = "B1"
Further to your comment about moving values between sheets, see my first example here, but always refer to the same workbook. If you find yourself repeatedly typing something like
ThisWorkbook.Sheets("MySheet").<other stuff>
then you can use the With shorthand.
With ThisWorkbook.Sheets("MySheet")
' Starting anything with a dot "." now assumes the with statement first
.Range("A1").Value = .Range("A2").Value
.Range("B1").Value = .Range("B2").Value
End With
Important to note is that this code has no data validation to check the cell's value before using it! Simply trying to insert a column based on a value which could be anything is sure to make the macro crash within its first real world use!
I have two sheets in an Excel workbook. I would like a VBA code to search for the content of cell J19 in Sheet2 and delete the column with the matching cell in Sheet1. I have been searching all around Google to look for some VBA codes, but I haven't found anything yet that works.
Does anybody here know how to do this? I have zero experience in VBA.
You could try this code to perform such a task.
Sub FindMatchAndThenDeleteColumn()
FindContent = Worksheets("Sheet2").Range("J19")
For Each Cell In Worksheets("Sheet1").UsedRange.Cells
If Cell.Value = FindContent Then Columns(Cell.Column).Delete
Next
End Sub
Put the code above in your workbook's module. Note that FindContent and Cell are randomly chosen here, you can use any names. I use
For Each Cell In Worksheets("Sheet1").UsedRange.Cells
to loop through every cell that is in use in Sheet1. It will check everything in the range from cell A1 to the last cell with data (the bottom right-most cell). If the content of cell J19 is a text, you can declare the variable FindContent as a String type, i.e. Dim FindContent As String. If it's a number, you can declare it as a Long type or a Single type or any number type that fits the content. Here I don't declare it which means it defaulting to a Variant type. And since you're a beginner in VBA, you may learn it from Excel Easy. Hope this helps.
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.
I have a custom macro function, declared in a Module :
Function myMacro(value as String) as String
myMacro = "Hello world " & value
End Function
This macro is inserted in a cell (A1 for example) and take the value of B2 as parameter.
Fx(A1 cell) = "MyMacro(B2)"
So my MyMacro func is triggered each time the value in B2 is changed, which is normal and is exactly what I want.
But i want to improve my macro to be more user friendly because my macro can take a long time (3 or 4 seconds) to execute. I want my macro to display "computing..." inside the resulting cell, before the real result is displayed.
To do that, my macro have to know on wich cell the compute is done. In the previous example, my macro need to know that the macro is triggered on the A1 cell.
The Application.Cell attrib contain the current cell (the one selected with the mouse), which is not always the cell containg the macro formula.
Is there a way for a VBA function to know which cell call the function ?
Application.Caller will return the range that the function is entered into. If the formula is array-entered into multiple cells, it will return the entire range containing the array. If you only want the individual cell containing the formula you can use Application.ThisCell.