1. 程式人生 > >除錯經驗——使用VBA分割駝峰式字串(Split Camel Case String)

除錯經驗——使用VBA分割駝峰式字串(Split Camel Case String)

需求:手頭有個幾千行的函式列表,每個函式名都採用駝峰式命名方式命名,如(GaussianSymplecticMatrixDistribution,

MultivariateHypergeometricDistribution)。為了分析各函式的分佈,需要將函式名拆分成單詞片語以便進行詞頻統計和資料分析。

程式碼:

Sub CamelCase()
Dim rCell As Range
Dim lCount As Long
 
With CreateObject("vbscript.regexp")
    .Pattern = "([a-z])([A-Z])"
    .Global = True
    For Each rCell In Selection
        lCount = .Execute(rCell).Count
        If lCount Then rCell.Resize(, lCount + 1) = Split(.Replace(rCell, "$1" & Chr(1) & "$2"), Chr(1))
    Next rCell
End With
End Sub

執行結果:


參考文章:

https://www.mrexcel.com/forum/excel-questions/369471-how-split-camelcase-text-cells.html