2017-05-08 49 views
0

我无法创建VBA以复制现有工作表并重命名具有特定后缀的副本。使用正则表达式模式使用VBA复制和重命名Excel工作表

现有工作表中的变量前缀(数字代码)后跟补丁后缀。

复制的工作表应该用相同的前缀重命名,后跟另一个修复后缀。

我想使用正则表达式来这样做,但我无法弄清楚如何用正则表达式指定表名。该模式可能仅仅是前缀[0-9]+

后缀总是相同的。

例子:
现有表:123_raw
新复制片:123_analyzed

这是我至今不知道如何去:

Dim objRegex As Object 
Set objRegex = CreateObject("vbscript.regexp") 
With objRegex 
    .Global = True 
    .Pattern = "[0-9]+" 

它应该看起来类似于这个我猜:

Sheets("regex pattern + [suffix]").Select 
Sheets("regex pattern + [suffix]").Copy After:=Sheets(3) 
Sheets("regex pattern + [suffix] (2)").Select 
Sheets("regex pattern + [suffix] (2)").Name = "regex pattern + [new suffix]" 

但我不知道如何实际编码。

任何帮助,非常感谢!

+6

你到目前为止试过了什么? – Tom

+0

你尝试过'替换'吗? –

+0

我刚刚更新了一些更具体的信息的问题。希望现在已经清楚了。 @Tom 我现在已经发布了迄今为止我所拥有的小代码。 – Jemba88

回答

0

假设你的表名是123_raw 456_raw还是什么[3 digits_words]所以你的模式将被Pattern = "([0-9]{3}\_)"https://regex101.com/r/Iu6nxn/1


enter image description here

enter image description here

([0-9]{3}\_)匹配单个字符存在于低于
0-909
{3}量词之间的范围中的单个字符的列表 - 精确匹配的3倍
\_的字符相匹配字面上(区分大小写)_


VBA代码示例那样简单,因为它可以 - 在这里,我们正在寻找的工作表名称123_[3 digits_words]复制和重命名为3 digits_analyzed

Option Explicit 
Public Sub Example() 
    Dim RegExp As Object 
    Dim Matches As Variant 
    Dim Pattern As String 
    Dim NewName As String 
    Dim Sht As Worksheet 

    Set RegExp = CreateObject("VbScript.RegExp") 

    For Each Sht In ThisWorkbook.Worksheets 
     Pattern = "([0-9]{3}\_)" ' Sheet name 123_ 

     With RegExp 
      .Global = False 
      .Pattern = Pattern 
      .IgnoreCase = True 
      Set Matches = .Execute(Sht.Name) 
     End With 

     If Matches.Count > 0 Then 
      Debug.Print Matches(0) ' Print on Immediate Win 

      NewName = Matches(0) & "analyzed" ' New sheet name 
      Sht.Copy After:=Sheets(3) ' Copy Sheet 
      ActiveSheet.Name = NewName ' Rename sheet with new name 

     End If 
    Next 

    Set RegExp = Nothing 
    Set Matches = Nothing 
    Set Sht = Nothing 
End Sub 
+1

像魅力一样工作!非常感谢! – Jemba88

0

像这样(其中_新替换es之前的后缀)

Sub B() 
Dim ws As Worksheet 
Dim objRegex As Object 

Set ws = Sheets(1) 
Set objRegex = CreateObject("vbscript.regexp") 

With objRegex 
    .Pattern = "([0-9]+)_[a-z]+" 
    If .test(ws.Name) Then 
     ws.Copy After:=Sheets(Sheets.Count) 
     ActiveSheet.Name = .Replace(ws.Name, "$1_new") 
    End If 
End With 

End Sub 
+0

我试过了,它没有给出任何错误。但是,我也没有看到任何新的工作表被添加。可能有一些缺失。但是,对于其他方面,这是有帮助的。非常感谢您的意见!非常感激! – Jemba88