code:
Public Sub CallDeleteAllText(control As IRibbonControl)
Call LeaveNumbers
End Sub
Public Function PullOnly(strSrc As String, CharType As String)
Dim RE As RegExp
Dim regexpPattern As String
Set RE = New RegExp
CharType = LCase(CharType)
Select Case CharType
Case Is = "digits":
regexpPattern = "\D"
Case Is = "letters":
regexpPattern = "\d"
Case Else:
regexpPattern = ""
End Select
RE.Pattern = regexpPattern
RE.Global = True
PullOnly = RE.Replace(strSrc, "")
End Function
Sub LeaveNumbers()
Dim cCell As Range
For Each cCell In Selection
If cCell <> "" Then
cCell.Value = "'" & PullOnly(cCell.Text, "digits")
End If
Next cCell
With Selection
.NumberFormat = "0"
.Value = .Value
End With
End Sub
此代码从单元格中删除所有文本,并保留所有数字。但是,要运行此代码,用户必须手动添加Microsoft VBScript Regular Expressions
中的Tools > References
引用。是否可以在代码本身中添加引用,以便首先添加引用,然后删除所有文本?
答案 0 :(得分:4)
将PullOnly函数中的这两行正则表达式声明和赋值更改为静态后期绑定。
Dim RE As RegExp
...
Set RE = New RegExp
'becomes,
static RE As object
...
if re is nothing then Set RE = createobject("VBScript.RegExp")
静态变量由声明它们的子过程或函数“记住”。通常,当函数完成并退出时,RE将被“遗忘”(并销毁)。但是,使用静态RE时,第二次(以及所有随后的所有时间)都会输入该函数,它“记住”该函数已被设置为regex脚本对象,因此无需再次设置。
这并不意味着静态var是全局公开的;它仅在声明它的函数或子过程中可用。