View Full Version : [vba] not in array
john_revelator
03-06-2009, 13:43
Ciao a tutti. Scusate la domanda sicuramente banale ma anche google non mi è stato d'aiuto.
Esempio
array = array(1,3,5)
for i = 1 to 10
if i not in array then
msgbox i
end if
next i
Come penso si intuisca lo scopo del codice è quello di stampare i numeri da 1 a 10 escludendo quelli definiti nell'array. L'intenzione è quella di evitare una serie lunghissima di and che nel mio caso reale sarebbe fastidioso. Quale costrutto posso usare? Ciao e grazie.
john_revelator
03-06-2009, 14:27
Continuando a cercare ho trovato una possibile soluzione
http://www.dailydoseofexcel.com/archives/2004/09/15/excluding-collection-members/
Sub exclusion()
Dim SheetsToKeep As String
Dim i As Long
Dim ws As Worksheet
‘Names of sheets to keep
‘note the last comma
SheetsToKeep = “Save1,Save2,Save3,”
‘Loop through the sheets
For Each ws In ThisWorkbook.Worksheets
‘See if the sheet’s name is in the string
‘don’t forget the comma
If InStr(1, SheetsToKeep, ws.Name & “,”) = 0 Then
ws.Delete
End If
Next ws
End Sub
che fa uso della funzione instr. Non dovessi trovare di meglio adotterò quella ma se esiste un modo più elegante ben venga. :)
Come penso si intuisca lo scopo del codice è quello di stampare i numeri da 1 a 10 escludendo quelli definiti nell'array.
Private Function TrovaInArray(valore As Variant, A() As Variant) As Long
Dim i As Long
For i = LBound(A) To UBound(A)
If valore = A(i) Then
TrovaInArray = i
Exit Function
End If
Next i
TrovaInArray = -1
End Function
Ritorna l'indice della prima occorrenza trovata nell'array passato come argomento. Se non trova occorrenze, ritorna -1.
E qui, come usarla :
Dim mioArray() As Variant
mioArray = Array(1, 3, 5)
Dim i As Integer
For i = 1 To 10
If TrovaInArray(i, mioArray) = -1 Then MsgBox i
Next i
;)
john_revelator
03-06-2009, 15:08
Ah, quindi non esiste nessun costrutto precotto e occorre costruirsi una funzioncina ad hoc. Mi inchino come sempre al tuo sapere. Grazie mille Marco. :)
Ah, quindi non esiste nessun costrutto precotto e occorre costruirsi una funzioncina ad hoc. Mi inchino come sempre al tuo sapere. Grazie mille Marco. :)
Beh, sì. VBA è più spartano, ma ovviamente non è una regola generale di VB.
in VB.NET ad esempio il tutto si ridurrebbe ad una riga di codice :
Dim mioArray() As Integer = {1, 3, 5}
For i As Integer = 1 To 10
If Not mioArray.Contains(i) Then MsgBox(i)
Next
:asd:
john_revelator
04-06-2009, 19:36
Decisamente più pratico. Bisogna che prenda coraggio e provi a iniziare a studiare vb.net. Grazie ancora. :)
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.