2010-09-28 14 views
4

Je voudrais écrire une fonction VBA qui a une plage en tant que paramètre facultatif. Par exemple quelque chose comme:Excel VBA - Utilisation des plages comme paramètres facultatifs pour les fonctions?

Public Function testfunc(S As String, Optional R As Range) As String 
testfunc = S 
For Each cell In R 
testfunc = testfunc + cell 
Next cell 
End Function 

J'ai essayé la fonction ci-dessus, mais j'ai #VALEUR! Erreur. J'ai également essayé d'encapsuler la boucle For dans une instruction If (R) Then ... End If.

Quelle serait la manière de traiter une plage optionnelle, où si la plage existe, elle est traversée par une boucle For Each?

Répondre

8

Essayez cette

Public Function testfunc(S As String, Optional R As Range = Nothing) As String 
    testfunc = S 
    if not R is nothing then 
     For Each cell In R 
      testfunc = testfunc & cell 
     Next cell 
    end if 
End Function 

J'ai testé ce correct dans Excel 2007. Vous devez le mettre dans un module, et non pas les sections de code feuille de calcul ou classeur. La fonction peut ensuite être appelée à partir de VBA avec ou sans objet Range ou en tant que fonction de feuille de calcul.

0

Solution:

Public Function testfunc(S As String, Optional R As String = vbNullString) As String 
    testfunc = S 

    If R <> vbNullString Then 
     For Each cell In Range(R) 
      ' & for concatenation not + ' 
      testfunc = testfunc & cell 
     Next cell 
    End If 
End Function 

Sub test() 
    MsgBox testfunc("", "A1:A5"), vbOKOnly, "Results" 
    MsgBox testfunc(""), vbOKOnly, "Results" 
End Sub