John Doe
John Doe

Reputation: 111

Caveat of not using "VBA." for standard functions

Is there any reason one would write VBA.Replace(), VBA.Instr() instead of just Replace(), Instr() when using these standard functions in VBA?

The only reason I can think of is when you declared functions with the same name in a custom module and you want to differentiate between them.

Edit: This example is answered, thanks to the link provided below (in short Len() is a keyword, not just a function). The example was bad since Len() is an exception.
Debug.Print VBA.Len(10) returns "2" while
Debug.Print Len(10) throws an error.

The original question remains, is there any caveat of not using the VBA. every time?

Upvotes: 0

Views: 74

Answers (1)

Hel O'Ween
Hel O'Ween

Reputation: 1486

You basically answered your own question: If you create a public method with the same name as a VBA method, it takes precedence over the VBA one. E.g. put this one in a module:

'------------------------------------------------------------------------------
'Purpose  : Override the VBA.CreateObject function in order to register what object
'           is being created in any error message that's generated.
'
'   Author: Darin Higgins
'   Source: http://www.darinhiggins.com/the-vb6-createobject-function/
'------------------------------------------------------------------------------
Public Function CreateObject(ByVal sClass As String, _
   Optional ByVal sServerName As String = vbNullString _
   ) As Object
   
   Dim sSource As String, sDescr As String, lErrNum As Long
   
   On Error Resume Next
   
   If Len(sServerName) Then
      Set CreateObject = VBA.CreateObject(sClass, sServerName)
   Else
      Set CreateObject = VBA.CreateObject(sClass)
   End If
   
   If VBA.Err Then
      sSource = VBA.Err.Source
      sDescr = VBA.Err.Description
      lErrNum = VBA.Err
      sDescr = sDescr & " (ProgID: " & sClass
      If Len(sServerName) Then
         sDescr = sDescr & ". Instantiated on Server '" & sServerName & "'"
      End If
      sDescr = sDescr & ")"
      
      On Error GoTo 0
      
      VBA.Err.Raise lErrNum, sSource, sDescr
   End If
   
   On Error GoTo 0
   
End Function

Steping through the code Set x = CreateObject("Object.Class") will step into this function instead of VBA.CreateObject.

Upvotes: 1

Related Questions