UDF to return formatted number - vba

Sometimes I like to display numbers along with text in the same cell. To do this, I custom format the cell to something like 0.00" test", e.g. a cell A1 with formula =PI(), but formatted with custom format 0.00" test" would return a displayed result of 3.14 test.
Crucially, the value of the cell is unchanged by the formatting - you can still do =A1 * 3 in another cell and get the result - since the value of A1 is still Pi, only it's display has changed.
For a UDF that returns a numerical value (in my case, Long, but it could be any number), is there a way of returning a cell such that it is displayed 1 way, but it's actual value (.Value2 in VBA I believe) is a number, not text.
I've tried Format( in VBA, but it returns a text string. I would just format my cell how I want it manually, but as you can see from the below code, the formatting is dependent on intermediate results (I'm trying to return the value formatted with the time the calculation took).
UDF_RESULT = Format(valueResult.Length, IIf(tElapsed < timeout, "0" & " """ & Round(tElapsed, 2) & "s""", "0"))
This would be easy to do with a Macro, but within a UDF it's harder. I could declare all of the intermediate values at a module level, then a Worksheet_Calculate() macro can access those values and apply the custom formatting, but a UDF-wrapped approach would be much better.

No.
You're confusing a cell's value with its number format. A UDF can compute a value, and the cell is free to format that value as needed.
So if a UDF returns a number, the cell's value is the result of that function - a number.
Just format the cell as needed. A function doesn't format anything.

Related

VBA Excel - Update Cell value based on other cell value

I am trying to write a formula in a Range of cells based on other range cells values from another worksheet. The formula is shown below:
ActiveSheet.Range("G14:G43").Formula = "=Worksheets("1ºperíodo").Range("V14:V43").Value"
But the code doesn't work and I get a syntax error. That must be related with the strings but I don't know how to fix it.
The value at V14 must be equal to the value at G14 until the last cell, i.e., the value at G14 equals the value at V43. Besides the syntax error is the formula correct based on what I expect to have?
"=Worksheets("1ºperíodo").Range("V14:V43").Value"
is not a formula. It is a value.
If you only want the static values then just assign the values:
ActiveSheet.Range("G14:G43").Value = Worksheets("1ºperíodo").Range("V14:V43").Value
If you want a live formula you need to pull vba from the string and use the .Address function:
ActiveSheet.Range("G14:G43").Formula = "=" & Worksheets("1ºperíodo").Range("V14").Address(0,0,,1)
But the above can be simplified to:
ActiveSheet.Range("G14:G43").Formula = "='1ºperíodo'!V14"
With the formula, we only need to refer to the first cell with a relative reference and vba will make the changes to each row.

Formula in worksheet and VBA works differently

Cell A1 contains the number 25, which is right-aligned, implying it's a number, not text.
D1 contains the formula:
="" & A1
The 25 in D1 is left-aligned, implying it's text. That is confirmed by the following formula, which returns 1:
=IF(D1="25",1,0)
The following VBA code puts 25 in F1 but the 25 is right-aligned and the IF test returns 0:
Range("F1") = "" & Range("A1")
Any explanation for the discrepancy?
E1 contains the following formula which gives a left-aligned 25 and the IF test returns 1:
TEXT(A1,"0")
However, the following code gives a right-aligned 25 and the IF test returns 0:
Range("F1") = Application.WorksheetFunction.Text(Range("A1"), "0")
Not that I have to use the TEXT function. I just wonder why it works differently than when in a worksheet.
Any rule that tells when or what worksheet functions won't work in VBA code, or more precisely, will give different results than when in worksheet?
When a data is written by vba into a cell, an internal type conversion function is called if required, that is if the data type is different from the cell's numberformat property.
You dont want that conversion function to be called.
To avoid this conversion function to be called, choose the proper Numberformat property for the cell before writing the data.
Range("b4").NumberFormat = "#"
Range("b4") = Application.WorksheetFunction.Text(Range("A1"), "0")
You simply get the wrong idea of what is a number in Excel.
in general ALL input is a string. Also writing "25" in a cell.
However: If possible, Excel will convert all inputs to a numerical value if possible. Also for dates and times.
To prevent this, you simply insert a ' in front of your "text" in the cell.
The confusing part for you is the different behavior for formulas.
A formula will always output a "result" AND the "data type".
So =1+1 will be numeric as the last action was math.
=Left(1+1,1) will be text as the last action was text-based.
For =A1 it will simply copy the type. If there is a formula, then this will be the same. But if there is a "direct input" it will always try to convert to numerical and only be text if it can't be converted or if it starts with a leading ' (A1 itself does this already).
As a result: If there is a plain 25 in the cell, it will always be "numerical" no matter "how" you input the 25.
For newer Excel there is only one exception: if the cell formatting is text prior to entering a number, it will be treated as text (no converting). This does not apply if you change the formatting later.
Simple test:
enter 25 in A1 (formatting general)
enter =ISNUMBER(A1) in A2 (will be TRUE)
set formatting for A1 to "text" (A2 will still be TRUE)
enter 25 in A1 (now A2 will become FALSE)
This may fail (Excel confuses itself sometimes here). Try it with a new sheet. ;)
Hopefully you understood the fault in your logic ;)
The cell alignment says nothing about the cell's contents. Forget about anything being "implied" by it. When you start on a virgin worksheet the format for all cells is "General" which means that Excel will decide the format of what you enter. If you enter a number the format will be "Number". If you enter what looks like a date to Excel the format will be "Date", and for most other things the format will be "Text".
So, if you enter " 25" in a cell formatted as "General" Excel will recognise this to be a number despite the leading spaces, read it is numeric, and format the cell to the right. This will happen regardless of whether you made the entry by hand or used VBA. You can then proceed to format the alignment as you wish.
However, if you enter the number 25 in a cell formatted as Text Excel will recognise the number as text and display it formatted to the left (unless you expressly formatted the horizontal alignment to the right).
The best way to deal with any problems you might encounter in this regard, set the NumberFormat and HorizontalAlignment properties for the cells that you want to write to. You can do that both manually or using VBA.
Worksheet function when used in the worksheet behaves / works the same way as when used in VBA. Consider below code:
Note: Range("B1") contains a numeric value 25
Dim r As Range, v As Variant
Dim wf As WorksheetFunction: Set wf = Application.WorksheetFunction
With Sheet1
Set r = .Range("B1")
v = r.Value2
v = wf.Text(r.Value2, "0")
End With
Now using the local window, let us check the data type of variant v.
SC1: All variables un-initialized
You can see, at the start that all variables have no value and the variant type v is empty.
SC2: Variables initialized and v assigned a value
After executing lines up to v = r.value2, all variable types were confirmed (e.g. Range/Range etc.) and variant v is now Variant/Double.
SC3: Re-assign a value on v but using worksheet function Text
Executing the last line which uses the worksheet function Text, variant v type becomes Variant/String. I think this confirms that the function Text works as expected converting the numeric 25 into a string type.
As for the behavior of passing VBA generated value to worksheet, it is covered by Docmarti's post above.

VBA script in excel to find and highlight text

I am looking for a VBA script that will help me find certain keywords in a cell and if found highlight the entire row. Below are my requirements:
I have a database of words eg hell, get out, shut up, don't you dare etc. I need a macro to search the data in column "E" of excel and in case any of the cell in column "E" contains any word listed in the database (irrespective of the case of the word upper or lower)the entire row is highlighted. The word can be in the beginning, middle or end of the cell and the macro should be able to find that word and highlight the column.
Seeking help from all VBA masters for this.
You can do this with conditional formatting, instead of VBA.
Conditional formatting works by applying a 'second formula' to a given cell. If the 'second formula' results in TRUE, then special formatting conditions can be applied.
EXAMPLE CONDITIONAL FORMATTING
For example, if you have a single column of Data, A:A, and you want to check if that column has the exact string "hello world", you could add a conditional format [Home ribbon, Styles section, Conditional Formatting] that turns a cell yellow with this formula:
=$A1="hello world"
This will only result in TRUE if the cell in column A at that row equals exactly "hello world" [note that Column A has an absolute-reference $, and row 1 does not, so row 1 is relative to the position of the cell in the condiitonal format rule].
To check to see if any row in column A includes hellow world, we need to add a SEARCH function, which checks to see if a small search string is inside of a larger string:
=SEARCH("hello world",$A1)>0
Because SEARCH by default returns the first character in a larger string that matches the search term (and if it finds nothing, it returns #N/A), we check to see if our search for "hello world" in column A returns a number.
SEARCHING MULTIPLE COLUMNS
Now, to see if ANY column, say from A-D, includes "hello world", we concatenate each value of each column so that it gives us a single string, which we can search through for "hello world", like so:
=SEARCH("hello world",$A1&$B1&$C1&$D1)>0
This will first create a single string, equal to A1 & B1 & C1 & D1 all in a row. Then it will search that newly created string to see if "hello world" is inside it, and return a number value if it is.
ARRAY FORMULA BASICS
Finally, we need to do the tricky part - searching for multiple terms instead of just "hello world". This is called an Array Formula. An array formula works by performing a single operation on multiple cells, and then returning multiple results in an Array. In an Excel sheet, an array formula must be confirmed with CTRL + SHIFT + ENTER (instead of just ENTER), but in conditional formatting, you actually don't need to do anything special - it will recognize an array formula without a special command.
As an example of conditional formatting, see this example, which checks whether any value from A1:A5 = 10, and if it does, it gives us the value in B1:B5:
=IF(A1:A5=10,B1:B5,"")
Remember in Excel on a worksheet, this would be confirmed by pressing CTRL + SHIFT + ENTER. If you do test this, it will give you the following result, assuming A2 = 10 and A5 = 10:
={"";B2;"";"";B5}
This result would actually be hidden, because Excel can't "collapse" an array function on its own. So assume column B had values, and we actually want to sum them together. We would then wrap the Array formula in a SUM function:
=SUM(IF(A1:A5=10,B1:B5,""))
As you can see if you test this, we have actually created our own SUMIF function, using Array formulas instead of the built-in SUMIF.
SEARCHING FOR MULTIPLE TERMS WITH ARRAY FORMULAS
So now we apply these principles to the conditional formatting, to create an array formula which will check our concatenated 'NEW STRING' for any number of provided terms, as follow [Assumes the search terms are typed into cells E1:E10]:
=SUM(SEARCH($E$1:$E$10,$A1&$B1&$C1&$D1)>0)
This formula can be placed as a conditional formatting rule which reaches all of A:D. Set the rule to highlight / change format in whatever way you like.

vba treat time as string

I am storing some values in my excel using vba and them comparing with other results. The results can be whatever: name, surname, address, time...
The problem that I have is that when I store a string that has a date format it takes it as time automatically. For example if I enter 8:15 it automatically convert it to 08:15 and then when I am comparing it with other value that is the same (8:15) it returns me false because it is not 08:15.
So basically the question is... how can I introduce a value like 8:15 without being converted to 08:15?
Two methods:
Put an apostraphe at the front of the value to tell Excel it's a string. Example: The value '8:15 will be interpreted as a string of value "8:15".
Use a formula to store the value as a string. Example: ="8:15" is also interpreted as a string of value "8:15".
I'm assuming this is when you're entering the values in Cells. the format of the cells is probably general, thus it formats things like numbers or dates different. Change it to text.
select all (or specific columns) right click - format cells - number tab - text option. it says there "text format cells are treated as text even when a number is in the cell. the cell is displayed exactly as entered"
edit
another option, in VBA use .FormulaR1C1 instead of .value when comparing. .value is the actual value of the cell (like a formula result) where as .formulaR1C1 will give you the actual entered text. so .formulaR1C1 might get you the actual entered 8:15 instead of the corrected value: 08:15.

Use formula as a string

I one cell I have to use several different formula depending on certains case.
I another sheet named Static, I wrote a Matrix of formulas in TEXT for all the cases.
My matrix have Criteria1 in rows Criteria2 in columns
So with INDEX/MATCH i will get the text formula for every scenario Criteria1/Criteria2.
Now I want to Evaluate this formula in text.
I did a custom function in VBA
Function Evalue(ByVal str As String)
Application.Volatile
Evalue = Evaluate(str)
End Function
It works when the function is in one block like SUM CONCATENATE etc... but not when there operation of function + -
Your UDF works for me........in A1 enter the text string:
sum(B2:B5)+sum(C4:C9)
in another cell:
=Evalue(A1) displays the correct value.