Reputation: 362
Recently, I have been tasked to build a solution that allows my teammates and I to quickly deal with what we call "Recipes". The unfortunate thing is that any other language like Python cannot be used because all the files are encrypted unless they are opened in specific programs. Excel is one of them and because of this our entire office is inclined to use VBA for everything. Coming from literally every language I've ever worked in, VBA is... Horrible to develop complex projects in (just an opinion), so I've ventured to make my (and my co-worker's) life easier by starting a library of various Types, Functions, Classes, etc.
For some reason, the following code will always execute the alreadyExists
Line
instead of only executing when the Error
is raised:
Private Sub SetName(index As Integer, name As String)
On Error GoTo alreadyExists
If (Not NameExists(name)) Then
internalName(index) = name
Else
Err.Raise 515, "SetName", "Name exists"
End If
alreadyExists:
MsgBox ("Name already exists in array.")
End
End Sub
Other Subs
handle this pattern just fine, but this one Sub
keeps running the alreadyExists
error. The Sub
that calls this would be:
Public Sub Insert(data As Variant, Optional name As String)
Dim i As Integer
If (Not internalData) = -1 Then
i = 0
Else
i = UBound(internalData) + 1
End If
Call ResizeTo(i)
If name = "" Then
internalName(i) = i
Else
SetName i, name
End If
internalData(i) = data
End Sub
If you feel like all the code is necessary then you can find it here.
Upvotes: 0
Views: 25
Reputation: 455
I used to have that kind of error, you have to put an Exit Sub
before the error handler otherwise it's going to be read like any other part of the code.
Private Sub SetName(index As Integer, name As String)
On Error GoTo alreadyExists
If (Not NameExists(name)) Then
internalName(index) = name
Else
Err.Raise 515, "SetName", "Name exists"
End If
Exit Sub
alreadyExists:
MsgBox ("Name already exists in array.")
End
End Sub
Upvotes: 1