How to write raw string in Excel VBA? - vba

I need to write a formula in an Excel sheet via VBA, so I go through select range and apply formula, but my formula is too long and it contain lot of double quotes (") so to ignore double quotes (") I am adding two double quotes (")
Some time string write as per my desire or some time by mismatching double quotes (") string get changed and formula applied is not correct.
As in python we write r before string and it work as follows:
print(r'hello\'s Sam.')
hello\'s Sam
but is there any way in Excel VBA to write such a raw string?
Formula is as below
=IF(NOT($E24=""),IF($Q24="0-10V(AI)","Direct (0-10V) = (0-100%)",IF($Q24="2-10V(AI)","Direct (2-10V) = (0-100%)",IF(OR($Q24="PT 1000",$Q24="NTC 20K"),"-50 to 150 Deg C","N/A"))),"")
And I apply it through VBA as follow
Sheet4.Range("R2:R50000").Formula = "=IF(NOT($E2=""" + """),IF($Q2=""" + "0-10V(AI)""" + ",""" + "Direct (0-10V) = (0-100%)""" + ",IF($Q2=""" + "2-10V(AI)""" + ",""" + "Direct (2-10V) = (0-100%)""" + ",IF(OR($Q2=""" + "PT 1000""" + ",$Q2=""" + "NTC 20K""" + "),""" + "-50 to 150 Deg C""" + ",""" + "N/A""" + "))),""" + """)"

There is no notion of raw string in VBA, but you could write the formula using e.g. single quote marks rather than double quote marks and then replace them. You could even make a simple utility function to do so:
Function r(s As String, Optional QuoteSymbol As String = "'") As String
r = Replace(s, QuoteSymbol, """")
End Function
Then your formula could be inserted simply as:
Sheet4.Range("R2:R50000").Formula = r("=IF(NOT($E2=''),IF($Q2='0-10V(AI)','Direct (0-10V) = (0-100%)',IF($Q2='2-10V(AI)','Direct (2-10V) = (0-100%)',IF(OR($Q2='PT 1000',$Q2='NTC 20K'),'-50 to 150 Deg C','N/A'))),'')")
In the off-hand chance that you need to have single quote marks in the final formula then you could pass something like the back-tick ( ` ) to the optional parameter QuoteSymbol
Having said all that, you seem to be doing more work than needed in the sense that inside a string any two consecutive double quotes are replaced by just one double quote. You don't need all of that concatenation to build up the final string.

Just add one quote(") as following example:
Formula:
=text(now(),"mmm dd yyyy")
VBA:
Sub InsertTodaysDate()
' This macro will put today's date in cell A1 on Sheet1
Sheets("Sheet1").Select
Range("A1").Select
Selection.Formula = "=text(now(),""mmm dd yyyy"")"
Selection.Columns.AutoFit
End Sub

As There is no notion of raw string in VBA, so this problem can solve with putting saw string in excel Cell and then use it in formula like
Sheet4.Range("R2:R50000").Formula = "=" & Cstr(Sheet10.Cells(1,2).Value)
next time only changing value in cell and formula get update

Related

VBA, string arguments in UDF that does not have quotation marks - how to access their value?

My function in a VBA is:
Function myFunc(a)
myFunc = a
End Function
When I use this function in Excel sheet in this way =myFunc("abc"), it is working, but when I use formula without pair of quotating marks =myFunc(abc), then I'm receiving error #NAME?.
Trying change argument from Function myFunc(a) to Function myFunc(chr(34) & a & chr (34) ) leads to error Expected: ).
How can I access a value that was typed without quotation marks in a UDF ( user defined function )?
Update: I need it to simplify usage of UDF for end user.
I don't know why do you need something like that. But it is possible! Read about Application.Caller - it's rng where UDF is running.
Private Function myFuncCalc(ByVal xstr As String)
' it is your main function to calculate what you want
' just sample code to test below
If xstr = "USD" Then
myFuncCalc = "yes it's american dollar!"
Else
myFuncCalc = "it's no american dollar"
End If
End Function
Function myFunc(a)
' function just to be available in worksheet
' and extracting currency letter codes from formula between brackets
bra1 = InStr(Application.Caller.Formula, "(")
bra2 = InStr(Application.Caller.Formula, ")")
x = Mid(Application.Caller.Formula, bra1 + 1, bra2 - bra1 - 1)
myFunc = myFuncCalc(x)
End Function
Voila!
If you use it without quotes, excel is expecting a named range. If what you want is to get the contents from another cell, you should define the argument as myfunction(a as Range) and then get its value using a.Value2 or a.Text.

How to add decimal and remove text from alphanumerical string

I have a huge amount of data which is alphanumerical and I need to convert it to purely numerical. Which no text in the string.
Ex.
C0424.100 ---> 424.100 (or 0424.100)
There always is 3 places after the decimal. Any tips on how to go about this? I'm pretty new to VBA. So basically I need to remove all text and a decimal with three digits to the right of it.
This is well described in String functions and how to use them
However, this should get you started. I would handle the formatting in Excel afterwards, but this is the simple string to number conversion. If the strings are more complex, consider using the Search string function to find the numbers, then use Right, Left, Mid functions to trim the string. Lastly use the CDbl() function to convert the string to the double.
Macro code as follows:
Sub temp()
'
' temp Macro
Range("A2").Select
stringToConvert = Selection.Value
trimmedString = Right(stringToConvert, Len(stringToConvert) - 1)
numberToDisplay = CDbl(trimmedString)
Range("A3").Value = numberToDisplay
End Sub
Do you even need VBA? If your data always has just one leading alpha character then you can just use standard Excel functions. For an entry in A2 that you want to convert, place the following formula in a convenient cell (e.g. B2):
=VALUE(RIGHT(A2,LEN(A2)-1))
I got UDF options for you.
Option 1: If you want to remove all the alphas from the beginning of string:
Function RemoveFirstAlphas(txt As String) As String
Dim i As Long
For i = 1 To Len(txt)
Select Case Mid$(txt, i, 1)
Case "0" To "9": Exit For
Case Else: Mid$(txt, i, 1) = Chr(32)
End Select
Next
RemoveFirstAlphas = Trim(txt)
End Function
Option 2: If you want to remove all the alphas from entire string:
Function RemoveAllAlphas(txt As String) As String
Dim ObjRegex As Object
Set ObjRegex = CreateObject("vbscript.regexp")
With ObjRegex
.Global = True
.Pattern = "[a-zA-Z\s]+"
RemoveAllAlphas = .Replace(Replace(txt, "-", Chr(32)), vbNullString)
End With
End Function
No need for VBA. Something like:
=--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),99)
will return the string starting with the first digit, and convert it to a numeric value. You can then format it in the cell however you wish.
The above will work with any number of non-digit leading characters. If will only have a single non-digit character, then #Skippy answer is simpler
If you have to have a VBA routine, something like the following should work -- it will extract the first numeric substring in the string. It does not matter if there are non-digits before or after. And, if there are no digits, the function will return the #NUM! error
Option Explicit
Function ExtractNums(S As String) As Variant
Dim I As Long
For I = 1 To Len(S)
If IsNumeric(Mid(S, I, 1)) Then
ExtractNums = Val(Mid(S, I))
Exit Function
End If
Next I
ExtractNums = CVErr(xlErrNum)
End Function

Excel VBA Using wildcard to replace string within string

I have a difficult situation and so far no luck in finding a solution.
My VBA collects number figures like $80,000.50. and I'm trying to get VBA to remove the last period to make it look like $80,000.50 but without using right().
The problem is after the last period there are hidden spaces or characters which will be a whole lot of new issue to handle so I'm just looking for something like:
replace("$80,000.50.",".**.",".**")
Is this possible in VBA?
I cant leave a comment so....
what about InStrRev?
Private Sub this()
Dim this As String
this = "$80,000.50."
this = Left(this, InStrRev(this, ".") - 1)
Debug.Print ; this
End Sub
Mid + Find
You can use Mid and Find functions. Like so:
The Find will find the first dot . character. If all the values you are collecting are currency with 2 decimals, stored as text, this will work well.
The formula is: =MID(A2,1,FIND(".",A2)+2)
VBA solution
Function getStringToFirstOccurence(inputUser As String, FindWhat As String) As String
getStringToFirstOccurence = Mid(inputUser, 1, WorksheetFunction.Find(FindWhat, inputUser) + 2)
End Function
Other possible solutions, hints
Trim + Clear + Substitute(Char(160)): Chandoo -
Untrimmable Spaces – Excel Formula
Ultimately, you can implement Regular expressions into Excel UDF: VBScript’s Regular Expression Support
How about:
Sub dural()
Dim r As Range
For Each r In Selection
s = r.Text
l = Len(s)
For i = l To 1 Step -1
If Mid(s, i, 1) = "." Then
r.Value = Mid(s, 1, i - 1) & Mid(s, i + 1)
Exit For
End If
Next i
Next r
End Sub
This will remove the last period and leave all the other characters intact. Before:
and after:
EDIT#1:
This version does not require looping over the characters in the cell:
Sub qwerty()
Dim r As Range
For Each r In Selection
If InStr(r.Value, ".") > 0 Then r.Characters(InStrRev(r.Text, "."), 1).Delete
Next r
End Sub
Shortest Solution
Simply use the Val command. I assume this is meant to be a numerical figure anyway? Get rid of commas and the dollar sign, then convert to value, which will ignore the second point and any other trailing characters! Robustness not tested, but seems to work...
Dim myString as String
myString = "$80,000.50. junk characters "
' Remove commas and dollar signs, then convert to value.
Dim myVal as Double
myVal = Val(Replace(Replace(myString,"$",""),",",""))
' >> myVal = 80000.5
' If you're really set on getting a formatted string back, use Format:
myString = Format(myVal, "$000,000.00")
' >> myString = $80,000.50
From the Documentation,
The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized.
This is why we must first remove the dollar sign, and why it ignores all the junk after the second dot, or for that matter anything non numerical at the end!
Working with Strings
Edit: I wrote this solution first but now think the above method is more comprehensive and shorter - left here for completeness.
Trim() removes whitespace at the end of a string. Then you could simply use Left() to get rid of the last point...
' String with trailing spaces and a final dot
Dim myString as String
myString = "$80,000.50. "
' Get rid of whitespace at end
myString = Trim(myString)
' Might as well check if there is a final dot before removing it
If Right(myString, 1) = "." Then
myString = Left(myString, Len(myString) - 1)
End If
' >> myString = "$80,000.50"

Changing decimal separator in VBA

I've written simple code in VBA (and seen questions here and here and none of these solutions work).
Dim toString As String
toString = cell.Value & "_"
If (InStr(toString, ",")) Then
toString = Replace(toString, ",", ".")
toString = Trim(toString)
cell.Value = " " + Left(toString, (Len(toString) - 1))
End If
Unfortunately, instead of string with dot separator, excel gives me double with comma in cell.Value. What curious is, when I exchange this whitespace with "_", it converts f. ex. 12,3 into _12.3. How can I fix it?
P.S. I add "_" at the end to ensure that toString will remain String.
I've had this issue before. You need to change the formatting of the cell before you write to it.
Application.Workbooks("Book1").Sheets("Sheet1").Range("A1:A100").NumberFormat = "#"
After that line runs you can simply write to the column like this:
Cells(1,1).Value = "12.3"
Excel will keep the string formatting and not convert it to a double.
Hope this helps.

VBA Excel: Concatenate a range of cells

I am trying to concatenate a range of cells along a single row. This group of cells has a defined start but a variable end. I tried doing this, but it didn't work. I'm still learning the Syntax of VBA but I haven't seen anything that says this WON'T work. Any help is appreciated.
Dim hexVal As String
For i = 4 To N + 3
Cells(3, i) = Application.WorksheetFunction.Dec2Hex(Cells(2, i), 2) & " "
Next i
hexVal = CONCATENATE(Range(Cells(3,i),Cells(3,N+3))
End Sub
You do not need Concatenate(), but using & instead:
for i = 4 to N + 3
hexVal = hexVal & cells(3,i)
next i
That is in case you are just concatenate the strings and you do know the range needs to be concatenate.
HEre's your problem:
CONCATENATE(Range(Cells(3,i),Cells(3,N+3))
The Cells method returns a range object, the default property of which is the .Value property. So, this is equivalent to:
CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value)
As such, it will ALWAYS FAIL unless those cells contain a valid address string.
Solution ... just use the built-in concatenator
hexVal = Range(Cells(3,i) & Cells(3,N+3))
Or:
hexVal = CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value))