Esempi VBA

Esempi VBA di Excel per principianti

Le macro sono il tuo migliore amico quando si tratta di aumentare la produttività o risparmiare tempo sul posto di lavoro. Dalle piccole attività alle grandi attività possiamo automatizzare utilizzando il linguaggio di codifica VBA. So che spesso potresti aver pensato ad alcune delle limitazioni di Excel, ma con la codifica VBA puoi eliminarle tutte. Ok, se hai lottato con VBA e sei ancora il principiante in questo articolo, forniremo alcuni degli utili esempi di codice VBA Macro in Excel.

Elenco dei primi 19 esempi

  1. Stampa tutti i nomi dei fogli
  2. Inserisci un indice di colore diverso in VBA
  3. Inserisci il numero di serie dall'alto
  4. Inserisci il numero di serie dal basso
  5. Inserisci numero di serie da 10 a 1
  6. Inserisci fogli di lavoro quanto vuoi
  7. Elimina tutti i fogli di lavoro vuoti dalla cartella di lavoro
  8. Inserisci riga vuota dopo ogni altra riga
  9. Evidenzia errore di ortografia
  10. Cambia tutto in caratteri maiuscoli
  11. Cambia tutto in caratteri minuscoli
  12. Evidenzia tutte le celle commentate
  13. Evidenzia tutte le celle vuote
  14. Nascondi tutti i fogli tranne un foglio
  15. Scopri tutti i fogli
  16. Elimina tutti i file nella cartella
  17. Elimina l'intera cartella
  18. Trova l'ultima riga utilizzata nel foglio
  19. Trova l'ultima colonna utilizzata nel foglio

Vediamo in dettaglio ciascuno di questo esempio.

Puoi scaricare questo modello Excel per esempi VBA qui - Modello Excel per esempi VBA

# 1 - Stampa tutti i nomi dei fogli

Codice:

 Sub Print_Sheet_Names () Dim i As Integer For i = 1 To Sheets.Count Cells (i, 1) .Value = Sheets (i) .Name Next i End Sub 

Questo estrarrà tutti i nomi dei fogli nel foglio attivo.

# 2 - Inserisci un indice di colore diverso in VBA

Codice:

 Sub Insert_Different_Colours () Dim i As Integer For i = 1 To 56 Cells (i, 1) .Value = i Cells (i, 2) .Interior.ColorIndex = i Next End Sub 

Questo inserirà i numeri da 1 a 56 e il loro indice di colore nella colonna successiva.

# 3 - Inserisci il numero di serie dall'alto

Codice:

 Sub Insert_Numbers_From_Top () Dim i As Integer For i = 1 To 10 Cells (i, 1) .Value = i Next i End Sub 

Questo inserirà i numeri di serie da 1 a 10 dall'alto.

# 4 - Inserisci il numero di serie dal basso

Codice:

 Sub Insert_Numbers_From_Bottom () Dim i As Integer For i = 20 To 1 Step -1 Cells (i, 7) .Value = i Next i End Sub 

Questo inserirà i numeri di serie da 1 a 20 dal basso.

# 5 - Inserisci il numero di serie da 10 a 1

Codice:

 Sottotitolo Ten_To_One () Dim i As Integer Dim j As Integer j = 10 For i = 1 To 10 Range ("A" & i) .Value = jj = j - 1 Next i End Sub 

Questo inserirà i numeri di serie da 10 a 1 dall'alto.

# 6 - Inserisci i fogli di lavoro quanto vuoi

Codice:

 Sub AddSheets () Dim ShtCount As Integer, i As Integer ShtCount = Application.InputBox ("How Many Sheets you wish to insert?", "Add Sheets",,,,,, 1) If ShtCount = False Then Exit Sub Else For i = 1 To ShtCount Worksheets.Add Next i End If End Sub 

Questo ti chiederà di inserire il numero di fogli di lavoro che desideri inserire. Basta specificare il numero nella casella di input e fare clic su Ok, inserirà immediatamente quei molti fogli.

# 7 - Elimina tutti i fogli di lavoro vuoti dalla cartella di lavoro

Codice:

 Sub Delete_Blank_Sheets () Dim ws As Worksheet Application.DisplayAlerts = False Application.ScreenUpdating = False For Each ws In ActiveWorkbook.Worksheets If WorksheetFunction.CountA (ws.UsedRange) = 0 Allora ws.Delete End If Next ws Application.DisplayAlerts = True Application .ScreenUpdating = True End Sub 

Questo eliminerà tutti i fogli di lavoro vuoti dalla cartella di lavoro su cui stiamo lavorando.

# 8 - Inserisci riga vuota dopo ogni altra riga

Codice:

 Sub Insert_Row_After_Every_Other_Row () Dim rng As Range Dim CountRow As Integer Dim i As Integer Set rng = Selection CountRow = rng.EntireRow.Count For i = 1 To CountRow ActiveCell.EntireRow.Insert ActiveCell.Offset (2, 0) .Seleziona Next i End Sub 

Per prima cosa, devi selezionare l'intervallo in cui desideri inserire righe vuote alternative.

# 9 - Evidenzia errore di ortografia

Codice:

 Sub Chech_Spelling_Mistake () Dim MySelection As Range For Each MySelection In ActiveSheet.UsedRange If Not Application.CheckSpelling (Word: = MySelection.Text) Then MySelection.Interior.Color = vbRed End If Next MySelection End Sub 

Innanzitutto, seleziona i dati ed esegui il codice VBA. Evidenzierà le celle che hanno errori di ortografia.

# 10 - Cambia tutto in caratteri maiuscoli

Codice:

 Sub Change_All_To_UPPER_Case () Dim Rng As Range for Each Rng In Selection.Cells If Rng.HasFormula = False Then Rng.Value = UCase (Rng.Value) End If Next Rng End Sub 

Innanzitutto, seleziona i dati ed esegui il codice. Convertirà tutti i valori di testo in caratteri maiuscoli.

# 11 - Cambia tutto in caratteri minuscoli

Codice:

 Sub Change_All_To_LOWER_Case () Dim Rng As Range per ogni Rng in Selection.Cells If Rng.HasFormula = False Then Rng.Value = LCase (Rng.Value) End If Next Rng End Sub 

First, select the data and run the code. It will convert all the text values to lower case characters in excel.

#12 – Highlight All the Commented Cells

Code:

 Sub HighlightCellsWithCommentsInActiveWorksheet() ActiveSheet.UsedRange.SpecialCells(xlCellTypeComments).Interior.ColorIndex = 4 End Sub 

Result: 

#13 – Highlight All the Blank Cells

Code:

 Sub Highlight_Blank_Cells() Dim DataSet As Range Set DataSet = Selection DataSet.Cells.SpecialCells(xlCellTypeBlanks).Interior.Color = vbGreen End Sub 

First, select the data range and run the code. It will highlight all the blank cells with green color.

#14 – Hide All Sheets Except One Sheet

Code:

 Sub Hide_All_Except_One() Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets If Ws.Name  "Main Sheet" Then Ws.Visible = xlSheetVeryHidden Next Ws End Sub 

The above code hides all the sheets except the sheet named as “Main Sheet”. You can change the worksheet name as per your wish.

#15 – Unhide All Sheets

Code:

 Sub UnHide_All() Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets Ws.Visible = xlSheetVisible Next Ws End Sub 

This will unhide all the hidden sheets.

#16 – Delete All Files in the Folder

Code:

 Sub Delete_All_Files() 'You can use this to delete all the files in the folder Test '' On Error Resume Next Kill "C:\Users\Admin_2.Dell-Pc\Desktop\Delete Folder\*.*" On Error GoTo 0 End Sub 

Change the folder path which is marked in red as per your folder deletion.

#17 – Delete Entire Folder

Code:

 Sub Delete_Whole_Folder() 'You can use this to delete entire folder On Error Resume Next Kill "C:\Users\Admin_2.Dell-Pc\Desktop\Delete Folder\*.*" 'Firstly it will delete all the files in the folder 'Then below code will delete the entire folder if it is empty RmDir "C:\Users\Admin_2.Dell-Pc\Desktop\Delete Folder\" 'Note: RmDir delete only a empty folder On Error GoTo 0 End Sub 

Change the folder path which is marked in red as per your folder deletion.

#18 – Find the Last Used Row in the Sheet

Code:

 Sub Last_Row() Dim LR As Long LR = Cells(Rows.Count, 1).End(xlUp).Row MsgBox LR End Sub 

Here we find the Last used Row in the Sheet

#19 – Find the Last Used Column in the Sheet

Code:

 Sub Last_Column() Dim LC As Long LC = Cells(1, Columns.Count).End(xlToLeft).Column MsgBox LC End Sub 

Here we find the Last used Column in the Sheet