|
作者是百度贴吧:XiaoJSoft,季文骢,whs_jwc@163.com
网址:http://tieba.baidu.com/p/1016980941
代码结构很不错,效率上如果有人有兴趣可以优化一下
我就是在作者分享的基础上,搭梯子下载了,然后做成过程,方便调用
- Sub GoBalance(ByVal strEquation As String, ByRef 配平结果 As String, ByRef 配平系数 As String)
- On Error Resume Next
- Dim strOut As String
- Dim lpCurrent As Long
- Dim bpResult As Boolean
- Dim rsBalanced() As Long
- Dim psSides As New Collection
- Dim psSide1 As New Collection
- Dim psSide2 As New Collection
- strEquation = RemoveSpace(strEquation)
- strEquation = ResolveStringCC(strEquation, "==", "=", "++", "+", "`", "", ".", "")
- If Trim(strEquation) = vbNullString Then
- MsgBox "请输入正确的化学方程式!!!"
- Exit Sub
- End If
- bpResult = BalanceCE(strEquation, rsBalanced())
- If bpResult = False Then
- MsgBox "无法配平此方程式,请检查!!!"
- Exit Sub
- End If
- ClearCollection psSides
- ClearCollection psSide1
- ClearCollection psSide2
- ResolveCommandEX Trim(strEquation), psSides, "="
- ResolveCommandEX psSides.Item(1), psSide1, "+"
- ResolveCommandEX psSides.Item(2), psSide2, "+"
- strOut = vbNullString
- For lpCurrent = 1 To psSide1.Count
- strOut = strOut & IIf(rsBalanced(lpCurrent) <> 1, Trim(Str(rsBalanced(lpCurrent))), "") & psSide1.Item(lpCurrent) & IIf(lpCurrent = psSide1.Count, "=", "+")
- Next lpCurrent
- For lpCurrent = 1 To psSide2.Count
- strOut = strOut & IIf(rsBalanced(psSide1.Count + lpCurrent) <> 1, Trim(Str(rsBalanced(psSide1.Count + lpCurrent))), "") & psSide2.Item(lpCurrent) & IIf(lpCurrent = psSide2.Count, "", "+")
- Next lpCurrent
- 配平结果 = strOut
- strOut = vbNullString
- For lpCurrent = 1 To UBound(rsBalanced())
- strOut = strOut & Trim(Str(rsBalanced(lpCurrent))) & IIf(lpCurrent = UBound(rsBalanced()), "", ",")
- Next lpCurrent
- 配平系数 = strOut
- End Sub
复制代码
'调用方法,也很简单
- Sub test()
- Dim strEquation$, str1$, str2$
- strEquation = "KMnO4=K2MnO4+MnO2+O2"
- GoBalance strEquation, str1, str2
- Debug.Print str1
- Debug.Print str2
- End Sub
复制代码
大神的代码见附件。 |
|