[英]Problems with function
我试图让工作表已经存在的警报工作,但是,我迷路了。 函数定义不正确还是?
Public Sub CopySheets()
Do
shName = InputBox("Please enter name of new project", "New Project")
If shName <> "" Then
shExists = SheetExists(shName) 'Check for existing sheet name
If Not shExists Then
Worksheets(Array(1, 2)).Copy After:=Sheets(Sheets.Count)
Else
MsgBox "Project Name:" & Space(1) & shName & " already exists", vbOKOnly + vbCritical, "Deter"
End If
End If
Loop Until Not shExists Or shName = ""
End Sub
Private Function SheetExists(ByVal sheetName As String, _
Optional ByVal wb As Workbook)
If wb Is Nothing Then Set wb = ActiveWorkbook
On Error Resume Next
SheetExists = Not wb.Worksheets(sheetName) Is Nothing
End Function
您忘记添加函数的类型。 它必须是boolean
Private Function
SheetExists(ByVal sheetName As String, _
Optional ByVal wb As Workbook) As Boolean
If wb Is Nothing Then Set wb = ActiveWorkbook
On Error Resume Next
SheetExists = Not wb.Worksheets(sheetName) Is Nothing
End Function
您的代码的问题是,如果工作表不存在,行SheetExists = Not wb.Worksheets(sheetName) Is Nothing
将引发错误,并且SheetExists
将保留其默认值为空作为函数的默认数据类型,而没有定义数据类型是variant
。 如果您将数据类型定义为boolean
则默认值将为False
。
恕我直言,这段代码虽然更长但更清晰
Private Function SheetExists(ByVal sheetName As String, _
Optional ByVal wb As Workbook) As Boolean
Dim ws As Worksheet
If wb Is Nothing Then Set wb = ActiveWorkbook
On Error GoTo EH
Set ws = wb.Worksheets(sheetName)
SheetExists = True
Exit Function
EH:
SheetExists = False
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.