Professional Documents
Culture Documents
VBA Tips
VBA Tips
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
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
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
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
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
End Function
Da usare così:
Dim nomeFile As String
nomeFile = "C:\Test.xls"
Dim NomeFileTest As String, LaPath As String, NomeFile1 As String, NomeFile2 As String ‘così posso
controllare qualsiasi file con la stessa function
if FileExist("C:\MioPercorso\MioFile.ext") then
' esiste
Else
' non Esiste
End If
fstat = FileStatus("C:\ppp.doc")
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
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