提问人:Mj0915 提问时间:2/14/2023 最后编辑:Mj0915 更新时间:2/15/2023 访问量:99
VBA Excel 递增的工作表名称 Add After 语句 使用存储的变量工作表名称
VBA Excel Incremented worksheet name Add After Statement using a stored variable sheet name
问:
如何在变量保存的特定工作表名称之后使用VBA在excel中添加工作表?
我试过了:Set sh = wb.Worksheets.Add(After:=wb.Sheets(wsPattern & CStr(n)))
先前递增的表名存储在“wsPattern & CStr(n)”中,新的表名从另一个语句和变量正确递增,但添加后失败,语法如下。我在这条线上出现超出范围的错误。
代码使用此语句完全执行,但在所有工作表的末尾添加任何给定系列中任何新创建的工作表:Set sh = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
由于工作簿现在有 4 个系列的工作表名称(例如 Test1、logistic1、Equip1、Veh1 等),它们在添加时会递增,因此需要将给定系列的下一个递增工作表添加到该工作表名称系列的末尾(Equip2 应该在 Equip1 之后),而不是在所有工作表的末尾。
Sub CreaIncWkshtEquip()
Const wsPattern As String = "Equip "
Dim wb As Workbook: Set wb = ThisWorkbook
Dim arr() As Long: ReDim arr(1 To wb.Sheets.Count)
Dim wsLen As Long: wsLen = Len(wsPattern)
Dim sh As Object
Dim cValue As Variant
Dim shName As String
Dim n As Long
For Each sh In wb.Sheets
shName = sh.Name
If StrComp(Left(shName, wsLen), wsPattern, vbTextCompare) = 0 Then
cValue = Right(shName, Len(shName) - wsLen)
If IsNumeric(cValue) Then
n = n + 1
arr(n) = CLng(cValue)
End If
End If
Next sh
If n = 0 Then
n = 1
Else
ReDim Preserve arr(1 To n)
For n = 1 To n
If IsError(Application.Match(n, arr, 0)) Then
Exit For
End If
Next n
End If
'adds to very end of workbook
'Set sh = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
'Test-Add After Last Incremented Sheet-
Set sh = wb.Worksheets.Add(After:=wb.Sheets(wsPattern & CStr(n)))
sh.Name = wsPattern & CStr(n)
End Sub
答:
0赞
CDP1802
2/15/2023
#1
创建函数
Sub Demo()
Dim s
s = AddSheet("SeriesName")
MsgBox s & " Added"
End Sub
Function AddSheet(sSeries As String) As String
Dim ws, s As String, i As Long, n As Long
With ThisWorkbook
' find last in series
For n = .Sheets.Count To 1 Step -1
s = .Sheets(n).Name
If s Like sSeries & "[1-9]*" Then
i = Mid(s, Len(sSeries) + 1)
Exit For
End If
Next
' not found add to end
If i = 0 Then
n = .Sheets.Count
End If
' increment series
s = sSeries & i + 1
.Sheets.Add after:=.Sheets(n)
.Sheets(n + 1).Name = s
End With
AddSheet = s
End Function
评论
0赞
CDP1802
2/15/2023
@Mj0915 谢谢,请注意,如果系列工作表的顺序不正确,它将失败。
评论
wsPattern
wsPattern & CStr(n)
Test2
n=1