Q: Which Excel VBA RegEx expression should I use to count decimal places?
Desired output
This is a table with some example input strings and the desired output.
INPUT DESIRED OUTPUT string max value unit decimal places -------------------------------------------------- 200A 200 A 0 110kV 110 kV 0 38,1MW 38,1 MW 1 38,1Mvar 38,1 Mvar 1 0-130°C 130 C 0 20-130°C 130 C 0 2000A 2000 A 0 10 kV 10 V 0 34,6MW 34,6 MW 1 34,6Mvar 34,6 Mvar 1 600A 600 A 0 114,3 MW 114,3 MW 1 114,3 Mvar 114,3 Mvar 1 2500A 2500 A 0 300A 300 A 0 500 A 500 A 0 100A 100 A 0
What I have done so far
Here you see a standalone Excel VBA code. The first sub is only for testing.
The function RegEx is my issue.
Sub TestRegEx()
strArray = Array("200 A", "200 A", "110 kV", "38,1MW", "38,1Mvar", _
"0-130°C", "2000 A", "10 kV", "34,6MW", "34,6Mvar", "600 A", _
"114,3 MW", "114,3 Mvar", "2500 A", "300 A", "500 A", "100 A")
For i = 0 To UBound(strArray)
Call RegEx(strArray(i))
Next
End Sub
Function RegEx(ByVal strInput As String)
Dim objRegEx As Object
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
'Show me the value
objRegEx.Pattern = "[^0-9_,]"
Debug.Print objRegEx.Replace(strInput, "")
'Show me the unit
objRegEx.Pattern = "[^A-Z_°]"
Debug.Print objRegEx.Replace(strInput, "")
'Show me the decimal places
objRegEx.Pattern = "?????"
Debug.Print objRegEx.Replace(strInput, "")
End Function
Hints
- I want to avoid normal VBA methods like InStr or looping through every character.
- Maybe the VBA
Lenmethod can be used to count the length of a string. But it will fail if there are zero decimal places, or? - For me, regular expressions are hard to read. All my knowledge is based on this MSDN article.
I am thankful for any help to my initial question on how to count decimal places.
PS: If you have suggestions for my other two RegEx strings for unit and value, please let me know. For example my value regex expression fails on “20-130°C”. I don’t know how to remove everything left from “-” to extract the value “130” only.
Try this:
UPDATE
To remove parts before
-, use the below function:UPDATE 2
The function to count decimal places:
Hope this helps.