
Para verificar se uma tabela variável contém os dados necessários, podemos percorrer todos os elementos dessa matriz, o que pode dar muito trabalho, ou utilizar algumas funções específicas para isso. Devemos levar em conta todas as possibilidades de erro e o número de dimensões da nossa variável matriz.
Function EstDans(palavra As String, Tabl) As Boolean
Dim Dimension As Byte, j As Integer
On Error Resume Next
If IsError(UBound(Tabl, 2)) Then Dimension = 1 Else Dimension = 2
On Error GoTo 0
Select Case Dimension
Case 1
On Error Resume Next
EstDans = Application.Match(palavra, Tabela, 0)
On Error GoTo 0
Case 2
For j = 1 To UBound(Tabl, 2)
On Error Resume Next
EstDans = Application.Match(palavra, Application.Index(Tabela, , j), 0)
On Error GoTo 0
If EstDans = True Then Exit For
Next
End Select
End Function
Sub test()
Dim Tb(), i As Integer
'tb 2 dimensions:
Tb = Range("A2:C16").Value
Debug.Print EstDans(MeuValor, Tb)
Erase Tb
'tb 1 dimension:
ReDim Preserve Tb(15)
For i = 0 To 14
Tb(i) = Cells(i + 2, 1)
Next
Debug.Print EstDans(MaValeur, Tb)
End Sub
A estrutura dessa função é similar à função Match:
Function LoopNaTabela(mot As String, Tb)
Dim Dimension As Byte, i As Long, j As LongOn Error Resume Next
If IsError(UBound(Tb, 2)) Then Dimension = 1 Else Dimension = 2
On Error GoTo 0
Select Case Dimension
Case 1
For j = LBound(Tb) To UBound(Tb)
If Tb(j) = palavra Then LoopNaTabela = True: Exit Function
Next
Case 2
For i = LBound(Tb, 1) To UBound(Tb, 1)
For j = LBound(Tb, 2) To UBound(Tb, 2)
If Tb(i, j) = palavra Then LoopNaTabela = True: Exit Function
Next j
Next i
End Select
End Function
Contra todas as probabilidades, Application.Match em tabelas grandes é muito menos eficiente do que o loop. Em testes:
Variável matriz de 2 dimensões:
Range("A1: Y20002")
Com Match: 8.300781 segundos
Com loop: 0,4375 segundo.
Variável matriz unidimensional:
Com Match: instantânea.
Loop: 0.015625 segundos
Em pequenas variáveis de tabela, ou em variáveis matrizes unidimensionais, a função com Application.Match é mais "elegante" e, às vezes, até mais rápida. Portanto, você deve considerar, em primeiro lugar, os dados a serem analisados.
Foto: © LINE ICONS - Shutterstock.com