Excel VBA – RegExp规范build议

我创build了以下REGEX来标记具有特定脚本标记的Excel文件(^ Joe Bloggs + JoeBloggs ^)。

但是,问题在于我不够聪明,无法改变下面的VBA脚本,因此用户可以指定要分析哪个特定的Excel列。

目前,下面的代码仅限于在列A:A上运行,我希望能够为列D:D运行它,或者按照用户input运行它。

Sub RegExp_1() Dim objRegex Dim RegMC Dim RegM Set objRegex = CreateObject("vbscript.regexp") With CreateObject("VBScript.RegExp") .MultiLine = True .Global = True .IgnoreCase = True .Pattern = "\^[\w\W\s]*\^|<[\W]{2,3}\^[\w\W\s]*\^[\W]{1,3}\>" For i = 1 To 10000 If .test(Cells(i, 1).Value) Then Set RegMC = .Execute(Cells(i, 1).Value) For Each RegM In RegMC Cells(i, 1).Characters(RegM.firstindex, RegM.Length + 1).Font.FontStyle = "Bold" Cells(i, 1).Characters(RegM.firstindex, RegM.Length + 1).Font.Size = 12 Cells(i, 1).Characters(RegM.firstindex, RegM.Length + 1).Font.ColorIndex = 5 Next End If Next i End With Call RegExp_2 Call RegExp_3 Call RegExp_4 MsgBox "Scripting tags have now been marked-up!" End Sub 

谢谢。

要在列D上运行此操作,只需将Cells(i,1)每个实例都更改为Cells(i,4)Cells的第一个参数表示行号,第二个参数表示列。 MSDN Worksheet.Cells属性

改变这个在任何给定的列上工作是多一点涉及,但不是非常如此。 假设用户在点击一个button时运行你的子程序,并且希望它运行在他们当前select的任何东西上。 (我对使用Selection对象有一个合理的理由感到很兴奋,你通常应该避免使用select 。)

我不知道你的正则expression式是匹配的,所以我无法testing这超越编译。 至less应该给你这个想法。

 Sub RegExp_1() Dim objRegex Dim RegMC Dim RegM Dim i As Long 'counter Dim rng As Range 'store the current selection Set rng = Selection Set objRegex = CreateObject("vbscript.regexp") With CreateObject("VBScript.RegExp") .MultiLine = True .Global = True .IgnoreCase = True .Pattern = "\^[\w\W\s]*\^|<[\W]{2,3}\^[\w\W\s]*\^[\W]{1,3}\>" For i = 1 To 10000 ' should change this to last row If .test(rng.Value) Then Set RegMC = .Execute(rng.Value) For Each RegM In RegMC rng.Characters(RegM.firstindex, RegM.Length + 1).Font.FontStyle = "Bold" rng.Characters(RegM.firstindex, RegM.Length + 1).Font.Size = 12 rng.Characters(RegM.firstindex, RegM.Length + 1).Font.ColorIndex = 5 Next End If Next i End With 'Call RegExp_2 'Call RegExp_3 'Call RegExp_4 MsgBox "Scripting tags have now been marked-up!" End Sub