我需要在Excel工作表的单元格中找到的字符串中添加括号。
例如,说我得到了:
913/(300+525)
我需要得到这个回报:
[913]/([300]+[525])
方程式非常简单,只需要处理+ - * / ( )
个字符。
我尝试使用MID
函数逐个字符地循环字符串,但是我无法使循环正常工作并最终得到乱七八糟的随机括号和数字。我也考虑使用正则表达式,但我以前从未使用它们,也不知道这是否是一个很好的应用程序。
如果您还有其他需要,请告诉我。谢谢你的时间!
他们可以长得很长。这是另一个例子:
我有:
(544+(1667+1668+1669+1670+1671+1672+1673)-1674)
但我需要:
([544]+([1667]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])
答案 0 :(得分:3)
我只是把它扔在一起,但它应该可以工作
Function generateBrackets(Equation As String) As String
Dim temp As String
Dim brackets As Boolean
Dim x 'If we're using Option Explicit, or just to be safe
For x = 1 To Len(Equation)
If Not IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
temp = temp & Mid(Equation, x, 1)
ElseIf Not IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
temp = temp & "]" & Mid(Equation, x, 1)
brackets = False
ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
temp = temp & "[" & Mid(Equation, x, 1)
brackets = True
ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
temp = temp & Mid(Equation, x, 1)
End If
Next x
generateBrackets = temp
End Function
答案 1 :(得分:2)
这是一种迎合十进制数的方法。
'~~> Add here whatever operators your equation
'~~> is likely to have
Const delim As String = "+()-/"
Sub Sample()
Dim MyAr
Dim sSamp As String
sSamp = "(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"
MyAr = Split(GetNewString(sSamp))
For i = 0 To UBound(MyAr)
sSamp = Replace(sSamp, MyAr(i), "[" & MyAr(i) & "]")
Next i
Debug.Print sSamp
End Sub
Function GetNewString(s As String) As String
Dim sTemp As String
sTemp = s
For i = 1 To Len(delim)
sTemp = Replace(sTemp, Mid(delim, i, 1), " ")
Next i
Do While InStr(1, sTemp, " ")
sTemp = Replace(sTemp, " ", " ")
Loop
GetNewString = Trim(sTemp)
End Function
<强>输入强>
"(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"
<强>输出强>
([5.44]+([16.67]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])