You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整现有VB正则表达式代码计算任意化学式的总原子数

VBA化学式总原子数计算实现

代码调整说明

原有代码的核心逻辑是从化学式中匹配所有元素及对应的数量,通过筛选特定元素返回对应计数。仅需移除特定元素的匹配判断,对所有匹配到的元素计数直接累加,同时保留原有的括号倍数处理逻辑,即可实现总原子数统计。

前置依赖

使用前请在VBA编辑器中依次点击「工具」→「引用」,勾选Microsoft VBScript Regular Expressions 5.5,启用正则表达式支持。

注意:请确保输入的化学式元素大小写符合化学规范,否则会出现识别错误。

调整后代码

Public Function CountTotalAtoms(ChemFormula As String) As Long
    Dim regEx As New RegExp
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
    End With
    
    ' 第一层匹配:匹配所有元素及对应数量
    regEx.Pattern = "([A][cglmrstu]|[B][aehikr]?|[C][adeflmnorsu]?|[D][bsy]|[E][rsu]|[F][elmr]?|[G][ade]|[H][efgos]?|[I][nr]?|[K][r]?|[L][airuv]|[M][cdgnot]|[N][abdehiop]?|[O][gs]?|[P][abdmortu]?|[R][abefghnu]|[S][bcegimnr]?|[T][abcehilms]|[U]|[V]|[W]|[X][e]|[Y][b]?|[Z][nr])([0-9]*)"
    
    Dim Matches As MatchCollection
    Set Matches = regEx.Execute(ChemFormula)
    
    Dim m As Match
    For Each m In Matches
        ' 移除元素判断,所有匹配到的元素计数直接累加
        CountTotalAtoms = CountTotalAtoms + IIf(Not m.SubMatches(1) = vbNullString, CLng(m.SubMatches(1)), 1)
    Next m
    
    ' 第二层匹配:处理带括号的基团,乘以对应倍数
    regEx.Pattern = "(\((.+?)\)([0-9]+))+?"
    Set Matches = regEx.Execute(ChemFormula)
    For Each m In Matches
        CountTotalAtoms = CountTotalAtoms + CountTotalAtoms(m.SubMatches(1)) * (CLng(m.SubMatches(2)) - 1)
        ' 减1是因为基团内的元素已经在第一层匹配中统计过一次
    Next m
End Function

使用示例

直接在单元格中输入公式即可调用,测试样例对应结果如下:

  • =CountTotalAtoms("CH3NO3") 返回 8
  • =CountTotalAtoms("CSe2") 返回 3
  • =CountTotalAtoms("C2Cl2") 返回 4
  • =CountTotalAtoms("C2H2BrF3") 返回 8
  • 支持带括号的化学式计算,例如=CountTotalAtoms("Ca(OH)2") 返回 5

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:48:03