I have a function that I want to call from a variety of modules. Whats the best way to do this in VB (excel).
module "SheetExists"
Function Name(SheetName As String) As Boolean
' returns TRUE if the sheet exists in the active workbook
SheetExists = False
On Error GoTo NoSuchSheet
If Len(Sheets(SheetName).Name) > 0 Then
SheetExists = True
Exit Function
End If
NoSuchSheet:
End Function
module "Main"
If Not SheetExists.Name("mySheet") Then
'do this
Else
' else do this
End If
I DONT want to have to do this or do I??
Call SheetExists.Name("mySheet")
Is that the only way to call a function from another module? Do I have to declare it as a Public function or something?
No, you don't have to do that, and you can call your function from anywhere.
Try this:
Put this code in Module1:
Sub TestSheetExists()
If SheetExists("Sheet1") Then
MsgBox "I exist!"
End If
End Sub
And this in Module2:
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
Obviously you can use whatever names for your modules you want.
EDIT: I see that calling from different modules still isn't working for you. Follow these steps exactly to set up a test workbook that should help you understand the problem.
In the Validation module, paste the following function:
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
Paste this sub into CallMe:
Sub TestSheetExistsFromCallMe()
If SheetExists("Sheet1") Then
MsgBox "I exist, and I was called from CallMe!"
End If
End Sub
Paste this into CallMeBack:
Sub TestSheetExistsFromCallMeBack()
If SheetExists("Sheet1") Then
MsgBox "I exist, and I was called from CallMeBack!"
End If
End Sub
Paste this into CallMeAgain:
Sub TestSheetExistsFromCallMeAgain()
If SheetExists("Sheet1") Then
MsgBox "I exist, and I was called from CallMeAgain!"
End If
End Sub
Press F5 to run the code from within CallMe. You should see the following messagebox:
Run the code from any of the 3 "Call" modules and you should see the corresponding messagebox.
I got the SheetExists function from Tim Williams (https://stackoverflow.com/a/6688482/138938) and use it all the time.
Functions declared in class modules must be preceded by the class name, e.g. class.function. Functions declared in ordinary modules have general scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With