【问题标题】:VBA Add a new sheet, if name exists add a numberVBA添加一个新工作表,如果名称存在添加一个数字
【发布时间】:2020-07-18 16:25:33
【问题描述】:

以下代码检查名为"Final" 的工作表是否存在,如果存在则创建另一个工作表,但名称取决于工作簿中工作表的数量。因此,如果只有一个名为 "Final" 的工作表和 10 个不同的工作表(总共 11 个工作表),宏将添加一个名为 "Final_12" 的新工作表。 如何修改代码以创建"Final_1""Final_2" 等。床单?

Set WSF = wb.Worksheets.Add(After:=wb.Worksheets(PayrollWS))
Set NewSht = ActiveSheet
newShtName = "Final"

'if "Final" sheet exists, there will be another added, e.g. "Final_2"
For Each Sht In wb.Sheets
    If Sht.Name = "Final" Then
        newShtName = "Final" & "_" & wb.Sheets.Count  'how to amend this part?
    End If
Next Sht

NewSht.Name = newShtName

【问题讨论】:

  • 创建该代码是其中之一,但是如何重命名表格?你会随机重命名吗?

标签: excel vba


【解决方案1】:

您需要计算Final 作为工作表名称存在的次数。

'if "Final" sheet exists, there will be another added, e.g. "Final_2"
Dim cnt as Long
For Each Sht In wb.Sheets
    If Left$(Sht.Name,5) = newShtName Then cnt = cnt + 1
Next Sht

NewSht.Name = newShtName & IIF(cnt>0, "_" & cnt, "")

【讨论】:

  • 怎么样:NewSht.Name = newShtName & (ThisWorkbook.Sheets.Count + 1)
【解决方案2】:

这段代码可以完成这项工作,它由一个子和一个函数组成

Sub NewFinalSheet()
Dim wsNew As Worksheet
If Not wsExits("Final") Then
    Set wsNew = thisworkbook.Worksheets.Add
    wsNew.Name = "Final"
    Exit Sub
End If

Dim i As Long, newWsName As String
Do
    i = i + 1
    newWsName = "Final_" & i
    If Not wsExits(newWsName) Then
        Set wsNew = ThisWorkbook.Sheets.Add
        wsNew.Name = newWsName
        Exit Sub
    End If
Loop
End Sub

你可以选择这两个之一的功能部分: 这更简单但更慢:

Function wsExits(shName As String) As Boolean
Dim ws As Worksheet

For Each ws In thisworkbook.Worksheets
    If ws.Name = shName Then
        wsExits = True
        Exit Function
    End If
Next ws

wsExits = False
End Function

这应该更快,但是是错误焦点

Function wsExits(shName As String) As Boolean
On Error GoTo NotE
If ThisWorkbook.Worksheets(shName).Name = shName Then
    wsExits = True
    Exit Function
End If

NotE:
    wsExits = False
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多