2009-05-28 17 views

risposta

6

E 'un modo un po' hacky per farlo in quanto si basa su aver impostato "On Error Resume Next", ma si potrebbe fare qualcosa di simile:

On Error Resume Next 
Dim objRef1, objRef2 
Set objRef1 = GetRef("DoStuff1") 
If objRef1 Is Nothing Then 
    Call objRef1 
Else 
    MsgBox "DoStuff1 is not defined!" 
End If 

Set objRef2 = GetRef("DoStuff2") 
If objRef2 Is Nothing Then 
    MsgBox "DoStuff2 is not defined!" 
Else 
    Call objRef2 
End If 

Sub DoStuff1 
    MsgBox "DoStuff1!" 
End Sub 

La chiamata alla GetRef genererà un'eccezione se la il sotto o la funzione a cui stai cercando di ottenere un puntatore non esiste (come nel caso di DoStuff2). È quindi possibile verificare se il riferimento è stato impostato come previsto.

+0

altrimenti sei in controllo Err.Number dopo aver tentato di chiamare la funzione. Ma poi la funzione che stai chiamando può essere definita, essere chiamata, ma essere la fonte dell'errore, che immagino non sia quello che vuoi. – Xiaofu

+0

Che funziona. Grazie! –

15

Ecco la mia soluzione che funziona secondo lo stesso principio, ma il hacky-ness è abbastanza autosufficiente:

Function FunctionExists(func_name) 
    FunctionExists = False 

    On Error Resume Next 

    Dim f : Set f = GetRef(func_name) 

    If Err.number = 0 Then 
     FunctionExists = True 
    End If 
    On Error GoTo 0 

End Function 
+2

Sì, è quello che ho finito con il fare. :-) –

+1

Si potrebbe semplificare questo a 'FunctionExists = (Err.Number = 0)' per impostare 'Boolean'. – Lankymart

+0

@Lankymart, non funziona allo stesso modo. Non sono sicuro perché no. –

Problemi correlati