Sintassi
MsgBox(prompt[, buttons] [, title] [, helpfile,
context])
Esempio di MsgBox
Sub prova1()
Msg = "Continuare ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "Dimostrazione MsgBox"
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
MyString = "Sì"
Else
MyString = "No"
End If
End Sub
Istruzione For Each...Next
Ripete un gruppo di istruzioni per ogni elemento
di una matrice o di un insieme.
Sintassi
For Each elemento In gruppo
[istruzioni]
[Exit For]
[istruzioni]
Next [elemento]
Sub Macro1()
Esempio di For each
Dim Found As Boolean
Dim OggettoMio, Collezione As Object
Found = False
Set Collezione = Range("a1:a4")
For Each OggettoMio In Collezione
If OggettoMio.Text = "Paolo" Then
Found = True
Exit For
End If
Next
If Found Then
Range("a10").Select
ActiveCell.Value = "Trovato"
Else
Range("a10").Select
ActiveCell.Value = "Non trovato"
End If
End Sub
Istruzione For...Next
Ripete un gruppo di istruzioni per il numero di volte
specificato.
Sintassi
For contatore = inizio To fine [Step incremento]
[istruzioni]
[Exit For]
[istruzioni]
Next [contatore]
Esempio di For ... Next
Sub Macro1()
Dim Parole, Caratteri, Stringa As String
For Parole = 10 To 1 Step -1
For Caratteri = 0 To 9
Stringa = Stringa & Caratteri
Next Caratteri
Stringa = Stringa & " "
Next Parole
Range("a1").Select
ActiveCell.Value = Stringa
End Sub
Istruzione Do…Loop (do while)
Ripete un blocco di istruzioni finché la valutazione
di una condizione dà come risultato True.
sintassi
Do [{While | Until} condizione]
[istruzioni]
[Exit Do]
[istruzioni]
Loop
Esempio di Do while
Sub prova1()
Dim Counter As Integer
Range("a1").Select
Counter = ActiveCell.Value
Do While Counter < 20
Counter = Counter + 1
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Offset(1, 1).Activate
ActiveCell.Value = Counter
Loop
End Sub
Istruzione Do…Loop (repeat until)
Ripete un blocco di istruzioni fino a quando
non dà come risultato True.
sintassi
Do
[istruzioni]
[Exit Do]
[istruzioni]
Loop [{While | Until} condizione]
Esempio di Repeat until
Sub prova()
Dim Check As Boolean, Counter As Integer
Check = True: Counter = 0
Do
Do While Counter < 20
Counter = Counter + 1
If Counter = 10 Then
Check = False
Exit Do
End If
Loop
Loop Until Check = False
End Sub
Istruzione While ... Wend
Ripete un blocco di istruzioni fin quando la
condizione è vera.
sintassi
While condizione
[istruzioni]
Wend
Esempio di While
Sub giorni()
oggi = Now()
Cells(1, 1) = oggi
Cells(1, 1).NumberFormat = "dd/mm/yy"
fine_anno = 38352
data = oggi + 7
i=1
While data < fine_anno
i=i+1
Cells(i, 1) = data
Cells(i, 1).NumberFormat = "dd/mm/yy"
data = data + 7
Wend
End Sub