'VBA to expand a logical Text String (Excel)
I came across a seemingly elegant solution to this problem online but i'm stuck
It seemed to be the ideal solution for something I’m working on. However, it seems to fail in a specific situation and I’m not familiar enough with regexp code to figure it out. The problem addressed was to expand a logical expression consisting of AND, OR logical expressions that may include parentheses. So for instance:
p and (q or r or s ) becomes p and q or p and r or p and s
i.e. p * (q + r + s) = pq + pr + p*s
The solution very cleverly replaced the OR/AND logic with arithmetic operators and with use of regular expressions got the correct results.
The problem seems to arise with the following type of input:
a * b * (c + d) should result in abc + abd
instead the code results in abc + b*d
See the original code here:
Function NoPar(ByVal s As String) As String
Dim regex1 As RegExp, regex2 As RegExp
Dim sMult As String
Dim v1 As Variant, v1Arr As Variant, v2 As Variant, v2Arr As Variant
' get rid of useless parentheses
Set regex1 = New RegExp
regex1.Pattern = "(^|[^*])\(([^()]+)\)(?!\*)"
' multiply with parentheses
Set regex2 = New RegExp
regex2.Pattern = "([^\(\)\+\*]+)\*\(([^\(\)]+)\)|\(([^\(\)]+)\)\*([^\(\)\+\*]+)|\(([^\(\)]+)\)\*\(([^\(\)]+)\)"
s = Replace(s, " ", "")
Do
Do While regex1.test(s): s = regex1.Replace(s, "$1$2"): Loop
If Not regex2.test(s) Then Exit Do
With regex2.Execute(s)(0)
v1Arr = Split(.SubMatches(0) & .SubMatches(2) & .SubMatches(4), "+")
v2Arr = Split(.SubMatches(1) & .SubMatches(3) & .SubMatches(5), "+")
sMult = ""
For Each v1 In v1Arr
For Each v2 In v2Arr
sMult = sMult & "+" & v1 & "*" & v2
Next v2
Next v1
If Mid(s, .FirstIndex + .Length + 1, 1) = "*" Then sMult = "(" & Mid(sMult, 2) & ")" Else sMult = Mid(sMult, 2)
s = Left(s, .FirstIndex) & sMult & Mid(s, .FirstIndex + .Length + 1)
End With
Loop
NoPar = s
End Function
the solution appears to work with added parentheses : a * b * (c + d) doesn't result in abc + abd but (a * b) * (c + d) does.
I imagine the key to getting this to work would be , at the start of the function to enclose any multiplicands that are not in brackets with brackets. But i'm not sufficiently versed in using regexp at this time.
By the way, Running this function in VBA needs the end user to set a reference to Microsoft VBScript Regular Expressions 5.5 in Tools references.
Thanks in advance for any assistance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
