VBA新手在这里 - 我已经梳理了互联网,似乎无法让它发挥作用,这让我感到难过。
我希望在表单上有一个按钮,允许用户在同一工作簿中生成“模板”工作表的副本 - 位于“模板”的右侧。我已经弄清楚了,我可以生成一个副本,将其自身重命名为Template(2)或生成一个以提示中输入的文本命名的空白工作表,但我不能同时做到这两个。
如下所示 - 它当前返回“Object Required”错误。在此先感谢您的帮助,非常感谢!
Private Sub NewSheet()
Dim NewSheet As Worksheet
Dim newName As String
Do
newName = Application.InputBox("What do you want to name the new sheet?", Type:=2)
If newName = "False" Then Exit Sub: Rem cancel pressed
Set NewSheet = ThisWorkbook.Worksheets("Template").Copy(After:=Worksheets("Template"))
On Error Resume Next
NewSheet.Name = newName
newName = Error
On Error GoTo 0
If newName <> vbNullString Then
Application.DisplayAlerts = False
NewSheet.Delete
Application.DisplayAlerts = True
MsgBox newName
End If
Loop Until newName = vbNullString
End Sub
答案 0 :(得分:0)
或者你可以试试这个:
Sub Test()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Template")
Dim newws As Worksheet, sh As Worksheet, newname
Dim query As Long, xst As Boolean, info As String
retry:
xst = False
newname = Application.InputBox("Enter a new sheet name.", info, , , , , , 2)
If newname = "False" Then Exit Sub
For Each sh In wb.Sheets
If sh.Name = newname Then
xst = True: Exit For
End If
Next
If Len(newname) = 0 Or xst = True Then
info = "Sheet name is invalid. Please retry."
GoTo retry
End If
ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname
End Sub
除非用户取消,否则会不断要求提供有效的工作表名称。
要避免删除新添加的工作表,请先检查名称是否有效。
此外,我认为您不能一次复制和分配,因为没有文档说明复制方法返回复制的对象。因此,首先复制并使用 Activesheet 将其分配给变量。