我想编写一个不允许添加具有相同名称的重复工作表的vba代码。我有一个代码分配给工作表上的按钮,用于更改活动工作表的名称。
表格从" Main"因此,所有工作表都将具有根据单元格A8和K11中选择的值重命名工作表的按钮(这两个单元格都有值下拉列表)。
我担心的是,当用户选择重命名工作表的按钮时,它应查找工作簿中的所有工作表,如果存在重复工作表则显示消息,否则应重命名工作表。我对传递价值感到困惑,我仍然是首发。请帮忙
Sub RenameCurrentSheet()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim ws As Worksheet
ThisWorkbook.Unprotect Password:="xyz"
For x = 1 To worksh
If ActiveSheet.Name = "MainSheet" Then
MsgBox "You Cannot Change Name of This Sheet!!!"
Exit For
Else
ActiveSheet.Name = Range("A8").Value & "-" & Range("K11").Value
Exit For
End If
Next x
Application.DisplayAlerts = True
ThisWorkbook.Protect Password:="xyz"
End Sub
答案 0 :(得分:0)
要遍历工作表,请使用以下代码:
dim wks as Worksheet
for I = 1 to Application.Worksheets.Count
set wks = Application.Worksheets(i)
Debug.Print wks.Name
.... whatever else you want do do
next i
set wks = Nothing ' When done with the object
答案 1 :(得分:0)
只需尝试并引用工作表以查看它是否存在 - 如果它抛出错误,则表单不存在。
您的代码失败,因为您一直在查看活动表,但从不更改哪个工作表处于活动状态。
Public Sub CopyAndRenameSheet()
Dim wrkSht As Worksheet
Dim sNewName As String
With ThisWorkbook
'Copy the template to the end of the workbook.
.Worksheets("MainSheet").Copy After:=.Sheets(.Sheets.Count)
'Set reference to last sheet in workbook (the one you've just copied).
Set wrkSht = .Worksheets(.Sheets.Count)
With wrkSht
'Get the new name from the ranges.
sNewName = .Range("A8") & "-" & .Range("K11")
If WorkSheetExists(sNewName) Then
MsgBox "You Cannot Change Name of This Sheet!!!", vbOKOnly + vbCritical
'Do something with the sheet, otherwise you'll be left with a
'sheet called something like "MainSheet (1)".
Application.DisplayAlerts = False
wrkSht.Delete
Application.DisplayAlerts = True
Else
.Unprotect Password:="xyz"
wrkSht.Name = sNewName
.Protect Password:="xyz"
End If
End With
End With
End Sub
Public Function WorkSheetExists(SheetName As String, Optional WrkBk As Workbook) As Boolean
Dim wrkSht As Worksheet
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
On Error Resume Next
Set wrkSht = WrkBk.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function
答案 2 :(得分:0)
此代码复制要从模板而不是ActiveSheet分配的名称。如果从活动工作表创建名称并确保该名称符合工作表名称的Excel要求,则此代码应该有效。