VBA

Visual Basic for Applications

by Andrea Spera

Automazione potente, soluzioni su misura.
VBA (Visual Basic for Applications) è un linguaggio di programmazione integrato in Microsoft Office, utilizzato per automatizzare processi e creare funzionalità personalizzate all'interno di applicazioni come Excel, Word e Access. Con VBA, è possibile creare macro, gestire dati, interagire con l'interfaccia utente e costruire soluzioni su misura per migliorare l'efficienza delle attività ripetitive.
Le Istruzioni condizionali
If Then
Dim myStr As String
    myStr = InputBox("a or b?")
    If myStr = "a" Then
        MsgBox "You choose: a"
    ElseIf myStr = "b" Then
        MsgBox "You choose: b"
    Else
        MsgBox "Invalid input"
    End If
While
Dim myIndex As Integer
    While (myIndex < 3)
        'something...
        myIndex = myIndex + 1
    Wend
For Next
Dim myIndex As Integer
    For myIndex = 0 To 3 Step 1
        'something..
    Next
Select Case
Dim myStr As String
    myStr = InputBox("a or b?")
    Select Case myStr
        Case "a"
            MsgBox "You choose: a"
        Case "b"
            MsgBox "You choose: b"
        Case Else
            MsgBox "Invalid input"
    End Select
Lavorare con gli array
Codice
Dim myArray As Variant
Dim myIndex As Integer
Dim myArrayDimension As Integer
    myArray = Array("one", "two", "ect...")
    myArrayDimension = UBound(myArray)
    myIndex = 0
    While myIndex <= myArrayDimension
        'do something...
        MsgBox "myArray(" & myIndex & ")= " & myArray(myIndex)
        myIndex = myIndex + 1
    Wend
Creare una finestra di conferma
Codice
Dim V_Warning As String
V_Warning = MsgBox("Sei sicuro?", 4)
If V_Warning = 6 Then
	'operazione da eseguire, se viene data la conferma
End If
Incolla valori
Codice
Public Sub IncollaSpeciale()
On Error GoTo Err
	Selection.PasteSpecial Paste:=xlPasteValues
	Exit Sub
Err:
	MsgBox ("si è verificato un errore")
	Exit Sub
End Sub
Costanti
Dichiarazione di una costante
Public Const myConst As Integer = 1
Costanti predefinite
vbCrLf: Ritorno a capo (Carriage Return + Line Feed).
vbTab: Tabulazione orizzontale.
Apri una cartella nell'esplora risorse
Codice
Shell "cmd /C start """" /max """ & myFolder & """", vbHide
Cartella Documenti di default
Codice
Dim myFolder As String
	'(Cartella "Documenti")
	myFolder = Application.DefaultFilePath
Controlla se un file esiste
Codice
Sub test()
	MsgBox fileExists (ThisWorkbook.Path & "\test.xlsx")
End Sub
Public Function fileExists(ByVal myFile As String) As Boolean
	fileExists = (Dir(myFile) <> "")
End Function
Cancella un file, se esiste
Codice
Public Function fileExists(ByVal myFile As String) As Boolean
	fileExists = (Dir(myFile) <> "")
End Function
Public Sub deleteFile(ByVal myFile As String)
	If fileExists(myFile) Then
		SetAttr myFile, vbNormal
		Kill myFile
	End If
End Sub
Apri, modifica, salva e chiudi una cartella di Excel
Codice
Sub test()
	editExcelFile "test.xlsx", "Ciao"
End Sub
Public Function editExcelFile(myFile As String, myString As String)
	Dim myWorkbook As Workbook
	Set myWorkbook = Workbooks.Open(myFile)
	Cells(1, 1) = myString
	myWorkbook.Save
	myWorkbook.Close SaveChanges:=False
End Function
Specifico per Excel
Crea, rinomina ed elimina fogli di lavoro
Crea un nuovo foglio
Public Sub NewSheet()
	Sheets.Add After:=Sheets(Sheets.Count)
End Sub
Elimina il foglio attivo, se non è l'unico
Public Sub DelSheet()
If Sheets.Count > 1 Then
	ActiveSheet.Delete
Else
	MsgBox ("La cartella contiene un solo foglio!")
End If
End Sub
Rinomina il foglio attivo
Public Sub RenameSheet()
	Dim i As Integer
	Dim n As String
	i = 1
	n = InputBox("Rinomina foglio", "Nuovo nome:", ActiveSheet.Name)
	While i < Sheets.Count
		If n = Sheets(i).Name Then
		MsgBox ("Esiste già un foglio con quel nome")
		Exit Sub
		End If
		i = i + 1
	Wend
	If IsNull(n) = False And n <> "" Then
		ActiveSheet.Name = n
	End If
End Sub
Protezione di un foglio di lavoro
Codice
Sub sheet_protection_true()
    sheet_protection ActiveSheet, True
End Sub
Sub sheet_protection_false()
    sheet_protection ActiveSheet, False
End Sub
Public Function sheet_protection(mySheet As Worksheet, myStatus As Boolean)
    If myStatus = True Then
        mySheet.Protect
    Else
        mySheet.Unprotect
    End If
End Function
Visualizzare di una serie di fogli
Codice
Public Sub SheetsVisibleNotVisible()
Dim Matrice_fogli As Variant
Dim DimensioneArray As Integer
Dim Indice As Integer
	Matrice_fogli = Array("Sheet1", "Sheet2", "Sheet3")
	DimensioneArray = UBound(Matrice_fogli, 1)
	For Indice = 0 To DimensioneArray Step 1
		Sheets(Matrice_fogli(Indice)).Visible = Not Sheets(Matrice_fogli(Indice)).Visible
	Next
End Sub
Visualizzare intestazioni delle righe e delle colonne
Codice
Sub display_headings_true()
    display_headings True
End Sub
Sub display_headings_false()
    display_headings False
End Sub
Public Function display_headings(myStatus As Boolean)
    ActiveWindow.DisplayHeadings = myStatus
End Function
Visualizzazione barra della formula
Codice
Sub display_formulaBar_true()
    display_formulaBar True
End Sub
Sub display_formulaBar_false()
    display_formulaBar False
End Sub
Public Function display_formulaBar(myStatus As Boolean)
    Application.DisplayFormulaBar = myStatus
End Function
Nascondere intere colonne
Codice
Sub hide_columns_true()
Dim fromCol As Integer
Dim toCol As Integer
    fromCol = InputBox("From column?")
    toCol = InputBox("To column?")
    hide_columns fromCol, toCol, True
End Sub
Sub hide_columns_false()
Dim fromCol As Integer
Dim toCol As Integer
    fromCol = InputBox("From column?")
    toCol = InputBox("To column?")
    hide_columns fromCol, toCol, False
End Sub
Public Function hide_columns(myColFrom As Integer, myColTo As Integer, myStatus As Boolean)
    Range(Cells(1, myColFrom), Cells(1, myColTo)).EntireColumn.Hidden = myStatus
End Function
Formattazione, adatta colonne, blocca celle, rimuovi formattazione
Formato numero, formato valuta, formato percentuale.
Public Sub FormatoNumero()
	Selection.NumberFormat = "#,##0"
End Sub

Public Sub FormatoValuta()
	Selection.NumberFormat = "$ #,##0"
End Sub

Public Sub FormatoPercentuale()
	Selection.Style = "Percent"
End Sub
Adatta colonne e blocca celle orizzontale.
Public Sub AdattaColonne()
	Cells.EntireColumn.AutoFit
End Sub

Public Sub BloccaOrizz()
	ActiveWindow.FreezePanes = False
	'reset evtl blocchi precedenti
	ActiveWindow.FreezePanes = True
End Sub
Questa funzione fa una pulizia della formattazione, eliminando eventuali bordi, allineamenti e colori.
Public Function sheetClear(myWorkbook As Workbook, mySheet As String)
With myWorkbook.Worksheets(mySheet)
	.Cells.EntireColumn.AutoFit
	.Cells.Borders.LineStyle = xlNone
	.Cells.HorizontalAlignment = xlGeneral
	.Cells.Interior.Pattern = xlNone
	.Cells.Interior.TintAndShade = 0
	.Cells.Interior.PatternTintAndShade = 0
	.Cells.Font.ColorIndex = xlAutomatic
	.Cells.Font.TintAndShade = 0
End With
End Function
Cartella corrente
Codice
Sub cartella_corrente()
MsgBox ThisWorkbook.Path
MsgBox ThisWorkbook.FullName
Dim mySeparator
    mySeparator = "/" 'or "/" for an url, for example in OneDrive
    '\ = Windows directory separator
    '/ = Unix path separator
    'https://stackoverflow.com/questions/38428561/difference-between-forward-slash-and-backslash-in-file-path
Dim myStr As String
    myStr = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, mySeparator) - 1)
        MsgBox "Path: " & myStr
    myStr = Right(ThisWorkbook.FullName, Len(ThisWorkbook.FullName) - InStrRev(ThisWorkbook.FullName, mySeparator))
        MsgBox "File name: " & myStr
End Sub
Aggiorna Tabelle Pivot
Codice
Public Sub AggiornaTutto()
	Dim myWorkbook As Workbook
		myWorkbook.RefreshAll
End Sub
Adatta larghezza colonne
Codice
ThisWorkbook.Sheets("Sheet1").Cells.EntireColumn.AutoFit
Elimina intera riga
Codice
Selection.EntireRow.Delete
Range con Cells
Codice
Cells(1, 1).Formula = "=TODAY()"
Range(Cells(1, 1), Cells(2, 2)).Value = 1