par , 17/01/2020 à 10h59 (1362 Affichages)
Préambule
Lorsque l'on souhaite utiliser un objet ListObject (tableau structuré en VBA), il est utile évidemment de s'assurer que celui-ci existe si l'on ne souhaite pas obtenir un message d'erreur lors de son utilisation.
Il y a plusieurs techniques possibles, j'en présenterai une sous forme de fonction nommée IsListObjectExist
Code de la procédure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| Function IsListObjectExist(ListName As String, Optional oWkb As Workbook) As Boolean
' Philippe Tulliez www.magicoffice.be
' Fonction renvoyant l'objet feuille où se trouve le tableau. Nothing s'il n'existe pas
' Arguments
' ListName Nom du tableau
' [oWkb] Objet Workbook où la recherche doit avoir lieu (ActiveWorkbook si omis)
' Déclaration
Dim cSht As Integer, cLst As Integer
' Assignation
If oWkb Is Nothing Then Set oWkb = ActiveWorkbook
'
With oWkb
Do
cSht = cSht + 1: cLst = 0
With .Worksheets(cSht)
Do While cLst < .ListObjects.Count And IsListObjectExist = False
cLst = cLst + 1
IsListObjectExist = StrComp(ListName, .ListObjects(cLst).Name, vbTextCompare) = 0
Loop
End With
Loop While cSht < .Worksheets.Count And IsListObjectExist = False
End With
End Function |
Code d'une procédure qui invoque cette fonction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Sub TestIsListObjectExist()
' Déclaration
Const TableName As String = "T_Sales"
Dim Text As Variant
Dim flag As Boolean
Dim msg As String
Dim TableWorkbook As Workbook
' Assignation
Text = Array("n'existe pas", "existe")
Set TableWorkbook = ThisWorkbook
'
flag = IsListObjectExist(TableName, TableWorkbook)
msg = "La table nommée [" & TableName & "] " & Text(Abs(flag))
MsgBox msg
'
Set TableWorkbook = Nothing
End Sub |