You are on page 1of 8

VBA Excel tips

Comandi sui File


Open
Workbooks.Open "c:\Pippo.xlsx"

Save
ActiveWorkbook.Save

Save as
ActiveWorkbook.SaveAs Filename:= _
Path & NomeFile, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False

Close
ActiveWorkbook.Close
ActiveWorkbook.Close False ‘senza salvare
Windows("Pippo.xlsx").Close False ‘anche se non è stato Activate

Selezione
Windows("Pippo.xlsx").Activate

NomeFile = ActiveWorkbook.Name

Screen Update
Application.ScreenUpdating = False / True

Comandi sugli Sheet


Selezione
Sheets("Foglio1").Select
ActiveCell.Offset(0, 1).Range("A1").Select ‘il primo numero è la riga, il secondo la colonna

Sheets(1).Select ‘selezione relativa del primo sheet, a prescindere da come è nominato

Esistenza
Dim IlFoglio As String
If wsExists(IlFoglio) = False Then
MsgBox "La cella selezionata non contiene il nome di uno Sheet esistente in questo file!", _
vbExclamation, "danaman prods" & ChrW(8482) & " developments"
Exit Sub
End If
Function wsExists(sFoglio As String) As Boolean
wsExists = Not IsError(Evaluate("'" & sFoglio & "'!A1"))
End Function

Sub ListSheets()
‘ scrivo partendo dalla casella selezionata tutti i nomi degli sheet presenti nel file
Dim ws As Worksheet
Dim x As Integer
Dim IlFoglio As String
x=1
For Each ws In Worksheets
IlFoglio = Sheets(x).Name
ActiveCell.Value = IlFoglio
ActiveCell.Offset(1, 0).Range("A1").Select
x=x+1
Next ws

End Sub

Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
WS_Count = ActiveWorkbook.Worksheets.Count 'Set WS_Count equal to the number of worksheets in the
active workbook.
'Begin the loop.
For I = 1 To WS_Count
' The following line shows how to reference a sheet within the loop by displaying the worksheet
name in a dialog box.
MsgBox ActiveWorkbook.Worksheets(I).Name
‘insert you code here…
ActiveWorkbook.Worksheets(I).Visible = True
Next I
End Sub

Sub WorksheetLoop2()
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
' Insert your code here.
' This line displays the worksheet name in a message box.
MsgBox Current.Name
Next
End Sub

Nascondi/Scopri
Sheets("ANPRA00F").Visible = True
Sheets("Pippo”).Select
ActiveWindow.SelectedSheets.Visible = False ‘funziona dopo il select della righe precedente

ActiveWorkbook.Worksheets("Foglio1").Visible = True
ActiveWorkbook.Worksheets(1).Visible = True ‘rende visibile il primo foglio

Delete
Sheets("Foglio1").Delete ‘mi avverte che contiene dati, se voglio cancellare senza alert vedi DISPLAY ALERTS

Filter Mode
Selection.AutoFilter
'controlla ev. presenza di filtro e lo toglie solo in caso sia attivo (con il false non funziona)
If ActiveSheet.AutoFilterMode = True Then
ActiveSheet.AutoFilter.Range.AutoFilter
End If

ActiveSheet.Range("$A$1:$H" & LastRow).AutoFilter Field:=2, Criteria1:=LaTabella

Dispaly Alerts
Application.DisplayAlerts = False
Sheets("Foglio1").Delete ‘for example
Application.DisplayAlerts = True

Stampa
Con questo mi setto quale era la stampante e la rimetto se la cambio per la stampa:
Dim StampantePredefinita As String
StampantePredefinita = Application.ActivePrinter
Setto una stampante e stampo:
Application.ActivePrinter = "Microsoft Print to PDF su Ne01:"
ActiveSheet.PrintOut
Application.ActivePrinter = StampantePredefinita

Con questa salvo sheet (non tutto il file) come .pdf, è veloce leggera e puoi settare il nome del file,
altrimenti con PrintOut non riesci:
Worksheets("pivot db totale").ExportAsFixedFormat Type:=xlTypePDF, _ ‘anche: ActiveSheet.Export…
Filename:="\\fasdac2kn\public\Ufficio Prestazioni\" & _
"Titolo" & ".pdf", _
Quality:=xlQualityStandard

Comandi sulle Celle/Riga/Colonna


Selezione Assoluta
Cella:
Range(“A1”).Select
Colonne:
Columns("A:W").EntireColumn.Select
Riga:
Rows("1:1").Select
Tutto:
Cells.Select

Selezione Relativa
ActiveCell.Offset(0, -1).Range("A1").Select 'prima la colonna, poi la riga
ActiveCell.Offset(0, 0).Range("A1").EntireColumn.Select 'seleziono la colonna dove mi trovo

Ultima riga
Dim LastRow As Double 'Integer a volte non va bene, anche se in teoria è da -2 miliardi a +2 miliardi (con
segno), vedi Riepilogo Tipi Dati
LastRow = Cells(Rows.Count, 2).End(xlUp).Row 'dove il numero corrisponde alla colonna dove va a vedere
ultima riga valorizzata

Ultima colonna
Dim EndCol As Integer
EndCol = Cells(1,Cells.Columns.Count).End(xltoLeft).Column

'dove il numero corrisponde alla riga dove va a vedere ultima colonna valorizzata

Converto da numero a lettera della colonna


'EndCol è il numero della colonna (vedi sopra)
Dim LetteraEndCol As String
'Nel codice chiami una function:
LetteraEndCol = LetteraColonna(EndCol)
'La function:
Function LetteraColonna(EndCol As Long) As String
Dim a
a = Split(Cells(1, EndCol).Address, "$")
LetteraColonna = a(1)
End Function

Assegno un valore
Range("B6").Select
ActiveCell.FormulaR1C1 = "pippo"
Oppure una formula:
Range("J2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-9],DATABASE_CB!C[-9]:C[-2],8,0)"

Cancello un valore
Selection.ClearContents
Oppure:
Range("N1").Value = ""
O meglio:
Range("A1:B20").ClearContents
Cancello tutto:
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select

Valuto se errore
If IsError(ActiveCell.Value) = True Then

Autofit (larghezza colonne)


Specifico:
Columns("A:W").EntireColumn.AutoFit
Oppure su tutte:
Cells.EntireColumn.AutoFit

Autofill (riempimento dati celle)


Con funzione di copia celle, non copia serie
Selection.AutoFill Destination:=Range("X1:Y20"), Type:=xlFillCopy

Comandi Copia Incolla


Range("A1:Z1000").Copy
Selection.Copy
ActiveSheet.Paste
Application.CutCopyMode = False
Incolla valori:
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Incolla formato:
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
(posso cancellare tutto e tenere solo il Paste:=xlPasteFormats)

Gestione dei file e delle directory


Controllo se un file è già aperto (tramite una function ed una riga di codice che richiama la function)
Codice originario dal web:
Private Function FileAperto(pathNomeFile As String) As Boolean

On Error Resume Next


Open pathNomeFile For Binary Access Read Write Lock Read Write As #1
Close #1
If Err.Number <> 0 Then
FileAperto = True
Err.Clear
End If

End Function

Da usare così:
Dim nomeFile As String
nomeFile = "C:\Test.xls"

If FileAperto(nomeFile) = True Then MsgBox "File già aperto!"

Che ho riadattato così:


Private Function FileAperto(NomeFileTest As String) As Boolean
On Error Resume Next
Open NomeFileTest For Binary Access Read Write Lock Read Write As #1
Close #1
If Err.Number <> 0 Then
FileAperto = True
Err.Clear
End If
End Function

Dim NomeFileTest As String, LaPath As String, NomeFile1 As String, NomeFile2 As String ‘così posso
controllare qualsiasi file con la stessa function

NomeFileTest = LaPath & NomeFile1


If FileAperto(NomeFileTest) = True Then
MsgBox "Il nome del file: " & NomeFile1 & " esiste già e il file è anche già APERTO."
Exit Sub
End If

Controllo se un file esiste


Tramite Function + Codice
Private Function FileExist(file As String) As Boolean
If Dir(file) <> "" Then
FileExist = True
Else
FileExist = False
End If
End Function

if FileExist("C:\MioPercorso\MioFile.ext") then
' esiste
Else
' non Esiste
End If

Controllo contemporaneamente se file esiste ed è aperto, dal web qui


Function FileStatus(FileName As String) As Variant
'Check file status; codice di ritorno:
'0=file libero, 70=file occupato, 53=file non esiste, 76=path non esiste
'altri errori: da indagare
'
Dim FileNum As Integer, ErrNum As Integer
'
On Error Resume Next ' Turn error checking off.
FileNum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open FileName For Input Lock Read As #filenum
Close FileNum ' Close the file.
ErrNum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
FileStatus = ErrNum
End Function

fstat = FileStatus("C:\ppp.doc")

‘Controllo se una directory è valida ed esiste


Dim LaPath As String
LaPath = “ … “
If (Len(Dir(LaPath, vbDirectory)) = 0) Then
MsgBox "Il percorso di rete valorizzato non è un percorso valido”
Exit Sub
End If

Riepilogo dei tipi di dati (Visual Basic)


https://docs.microsoft.com/it-it/dotnet/visual-basic/language-reference/data-types/

MsgBox
Tipologia:
vbInformation, vbExclamation, vbCritical
Per andare a capo:
" & vbNewLine & “
Per inserire carattere speciale (questo è il ™):
" & ChrW(8482) & "
Esempio:
MsgBox "Il nome del file: " & NomeFile & " esiste già" & vbNewLine & "CHIUDERE il file.", _
vbExclamation, "danaman prods" & ChrW(8482) & " developments"
Con IIF integrata:
MsgBox "*** Elaborazione terminata con successo! ***" & vbNewLine & _
"Orario inizio processo: " & OraInizio & vbNewLine & _
"Orario fine processo: " & OraFine & vbNewLine & _
IIf(CreazioneSheetScarti = True, "ATTENZIONE! Verificare problema non gestibile", ""), _
vbInformation, "danaman prods" & ChrW(8482) & " developments"

Con risposta:
'chiedo se vuoi fare qualcosa
Dim Risposta As VbMsgBoxResult
Risposta = MsgBox("Vuoi procedere?", vbYesNo)
If Risposta = vbYes Then
GoTo procedi
Else: GoTo salta
End If

Prova anche questa (senza definizione parametro) che funziona su Access:


If MsgBox("Type your message here", vbYesNo) = vbYes Then …
If MsgBox("OK o Cancel?", vbOKCancel, "ATTENZIONE!") = vbCancel Then

Comandi su Tabella Pivot


Aggiorna dati della Pivot:
ActiveSheet.PivotTables("Tabella pivot3").PivotCache.Refresh

Invio e-mail
Dim Allegato1 as string, Allegato2 as string
Dim NewMail As Object
Set NewMail = CreateObject("Outlook.Application").CreateItem(oMailItem)
With NewMail
.To = "manueledanastasio@gmail.com; manuele.danastasio@fasdac.it"
'Worksheets("Elenco").Range("C2") se voglio puntare dinamicamente a una cella
'.CC = indirizzo in copia per conoscenza, se mi serve. qui è commentato
.Subject = "Invio di prova"
.Body = "Potrebbe essere il riferimento a una cella, così sarebbe un testo variabile"
.Attachments.Add Allegato1
.Attachments.Add Allegato2
'.Send ‘invia direttamente
.Save ’salva in bozze
End With
Set NewMail = Nothing
Debug shortcuts
Keystroke Description

Shift-F2 Definition: Put the cursor on the variable, procedure, or


property in question and press [Shift-F2] to see where it’s
defined. You’ll jump directly to it. You can do this as often as
you like to understand how your code works.
Ctrl-Shift- Go back to where you came when you pressed [Shift F2]
F2
F9 Set (or reset) a breakpoint to stop the program when it gets to
this line
F5 Run the current procedure (if it doesn’t require parameters)
F8 Run the current line
Shift-F8 Step over the line by running the procedure on the current line
without going into it and stepping through each line
Ctrl-Shift- Run through the rest of the current procedure (useful if you no
F8 longer need to examine the procedure)
Ctrl-F9 Set the next statement (jump over existing code)

You might also like