|
借鉴修改一下,现在能用内置的INT等函数了,分享一下思路,这个代吗应该还有精简改进的空间滴
- '自动计算
- Function tn(R As String, Optional n As Variant) As Variant
- Dim PL As String, PR As String, PL2 As String, PR2 As String, PL21 As String, PL22 As String
- Dim PL2rl As Integer '+
- If IsMissing(n) Then Else If n <> Int(n) Or n < 0 Then GoTo a4
- Do
- If InStr(R, "[") > InStr(R, "]") Then GoTo a4
- If InStr(R, "[") = 0 Then Exit Do
- PL = Left(R, InStr(R, "]") - 1)
- PR = Right(R, Len(R) - InStr(R, "]"))
- PL2 = Left(PL, InStrRev(PL, "[") - 1)
- R = PL2 & PR
- If InStr(R, "]") = 0 Then Exit Do
- Loop
- R = StrConv(R, vbNarrow) '把计算式里的全角“(”、“)”都转化为半角“(”、“)”
- R = Replace(R, "K", "^(.5)")
- R = Replace(R, "F", "^(2)")
- R = Replace(R, "÷", "/")
- R = Replace(R, "×", "*")
- If Len(R) > 255 Then GoTo a1
- Zhuhanshu:
- On Error GoTo a4
- If IsMissing(n) Then
- tn = Round(Evaluate(R), 3)
- Else
- tn = Round(Evaluate(R), n)
- End If
- Exit Function
- If 1 = 2 Then
- a1:
- On Error GoTo a4
- If InStr(R, "(") = 0 Then GoTo a2
- Do
- PL = Left(R, InStr(R, ")"))
- PR = Right(R, Len(R) - InStr(R, ")"))
- If IsNumeric(Left(PR, 1)) Or Left(PR, 1) = "(" Or Left(PR, 1) = "." Then GoTo a4
- PL2 = Left(PL, InStrRev(PL, "(") - 1)
- PR2 = Right(PL, Len(PL) - InStrRev(PL, "(") + 1)
- If Right(PL2, 1) <> "*" Or Right(PL2, 1) <> "/" Or Right(PL2, 1) <> "+" Or Right(PL2, 1) <> "-" Then
- PL2rl = Application.Max(InStrRev(PL2, "*"), InStrRev(PL2, "/"), InStrRev(PL2, "+"), InStrRev(PL2, "-")) '+
- PL21 = Left(PL2, PL2rl) '+
- PL22 = Right(PL2, Len(PL2) - PL2rl) '+
- PL2 = PL21
- PR2 = PL22 & PR2
- End If
- R = PL2 & Evaluate(PR2) & PR
- If Len(R) <= 255 Then GoTo Zhuhanshu
- If InStr(R, "(") = 0 Then GoTo a2
- Loop
- End If
- If 1 = 2 Then '无()时
- a2:
- On Error GoTo a4
- If InStr(R, "+") = 0 And InStr(R, "-") = 0 Then GoTo a3
- Do
- PL = Left(R, 255)
- If InStrRev(PL, "+") > InStrRev(PL, "-") Then
- PL2 = Left(PL, InStrRev(PL, "+") - 1)
- R = Evaluate(PL2) & Right(R, Len(R) - InStrRev(PL, "+") + 1)
- Else
- PL2 = Left(PL, InStrRev(PL, "-") - 1)
- R = Evaluate(PL2) & Right(R, Len(R) - InStrRev(PL, "-") + 1)
- End If
- If Len(R) <= 255 Then GoTo Zhuhanshu
- If InStr(R, "+") = 0 And InStr(R, "-") = 0 Then GoTo a3
- Loop
- End If
- If 1 = 2 Then
- a3:
- On Error GoTo a4
- Do
- PL = Left(R, 255)
- If InStrRev(PL, "*") > InStrRev(PL, "/") Then
- PL2 = Left(PL, InStrRev(PL, "*") - 1)
- R = Evaluate(PL2) & Right(R, Len(R) - InStrRev(PL, "*") + 1)
- Else
- PL2 = Left(PL, InStrRev(PL, "/") - 1)
- R = Evaluate(PL2) & Right(R, Len(R) - InStrRev(PL, "/") + 1)
- End If
- If Len(R) <= 255 Then GoTo Zhuhanshu
- Loop
- End If
- If 1 = 2 Then
- a4:
- If R = "" Then tn = 0 Else tn = "错误"
- If R = "密码" Then tn = "不能让你看"
- End If
- End Function
复制代码
|
|