I got a simple question related to programming in Excel for the programming guru's out there. I created an offer template which generates up to 10 sheets. Everytime the user generates the offer sheets, the old sheets will be deleted first, and then new sheets will be generated.
To seal any unwanted errors off i created a "Sub" and a Function to create new sheets, which return an error if the sheet already exists. Im not sure which of the two to use. (no one to discuss it with either.)
so the questions are:
- which method is preferred and why
- would you solve it different
i suppose i could also use a For Each [sheet] ..Next statement to check if a sheet exists and even cancel the event before the sheet(x).copy occurs.
But then still i want to return some boolean value from my "create sheet" subroutine to my main routine
Sub MyTestProc()
Dim strsheet As String
Dim bolSuccess As Boolean
'test1
strsheet = ActiveSheet.Name
Create_New_sheet strsheet, bolSuccess
If bolSuccess Then
'we dont expect any success here
Else
MsgBox "fail..."
End If
End Sub
'__________________________________________________________________
Sub Create_New_sheet(ByVal strsheet As String, ByRef Success As Boolean)
'ByRef returns the value of Success to the input Boole value
On Error GoTo ShtError
ActiveSheet.Copy After:=Sheets(Sheets.Count)
With ActiveSheet
.Name = strsheet 'raises error
End With
Success = True
On Error GoTo 0
ShtError:
Select Case Err.Number
Case 0 'whee
Case 1004 'the sheet exists
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
MsgBox "Could not create sheet!" & vbCr & _
Err.Number & " - " & Err.Description, vbExclamation, app
Case Else 'someone poisoned the waterhole
MsgBox "Some unknown exception...yadda yadda." & vbCr & _
Err.Number & " - " & Err.Description, vbExclamation, app
End Select
End Sub
Sub MyTestProcA()
'test function
Dim strsheet As String
Dim bolSuccess As Boolean
strsheet = ActiveSheet.Name
If Create_New_sheetA(strsheet) Then
'we dont expect a success with this code
Else
MsgBox "fail..."
End If
End Sub
'__________________________________________________________________
Function Create_New_sheetA(ByVal strsheet As String) As Boolean
On Error GoTo ShtError
ActiveSheet.Copy After:=Sheets(Sheets.Count)
With ActiveSheet
.Name = strsheet 'raises error
.UsedRange = .UsedRange.Value
End With
On Error GoTo 0
ShtError:
Select Case Err.Number
Case 0 'whee
Case 1004 'the sheet exists
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
MsgBox "Could not create sheet!" & vbCr & _
Err.Description, vbExclamation, app
Case Else 'someone poisoned the waterhole
MsgBox "Some unknown exception...yadda yadda." & vbCr & _
Err.Number & " - " & Err.Description, vbExclamation, app
End Select
End Function
Bookmarks