Ejemplos de VBA

Ejemplos de Excel VBA para principiantes

Las macros son sus mejores amigas cuando se trata de aumentar su productividad o ahorrar algo de tiempo en su lugar de trabajo. Desde pequeñas tareas hasta grandes tareas, podemos automatizar utilizando el lenguaje de codificación VBA. Sé que a menudo puede haber pensado en algunas de las limitaciones que tiene Excel, pero con la codificación VBA puede eliminar todas esas limitaciones. De acuerdo, si tuvo problemas con VBA y aún es un principiante en este artículo, le daremos algunos de los ejemplos útiles del código de macro VBA en Excel.

Lista de los 19 ejemplos principales

  1. Imprimir todos los nombres de las hojas
  2. Insertar índice de color diferente en VBA
  3. Inserte el número de serie desde arriba
  4. Inserte el número de serie desde abajo
  5. Inserte el número de serie del 10 al 1
  6. Inserte hojas de trabajo tantas veces como desee
  7. Eliminar todas las hojas de trabajo en blanco del libro de trabajo
  8. Insertar fila en blanco después de cada fila
  9. Resaltar error ortográfico
  10. Cambiar todo a caracteres en mayúsculas
  11. Cambiar todo a minúsculas
  12. Resalte todas las celdas comentadas
  13. Resalte todas las celdas en blanco
  14. Ocultar todas las hojas excepto una
  15. Mostrar todas las hojas
  16. Eliminar todos los archivos de la carpeta
  17. Eliminar toda la carpeta
  18. Encuentre la última fila utilizada en la hoja
  19. Encuentre la última columna utilizada en la hoja

Veamos cada uno de estos ejemplos en detalle.

Puede descargar esta plantilla de Excel de ejemplos de VBA aquí - Plantilla de Excel de ejemplos de VBA

# 1 - Imprimir todos los nombres de las hojas

Código:

 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 

Esto extraerá todos los nombres de las hojas a la hoja activa.

# 2 - Inserte un índice de color diferente en VBA

Código:

 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 

Esto insertará números del 1 al 56 y su índice de color en la siguiente columna.

# 3 - Inserte el número de serie desde arriba

Código:

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

Esto insertará números de serie del 1 al 10 desde la parte superior.

# 4 - Inserte el número de serie desde abajo

Código:

 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 

Esto insertará números de serie del 1 al 20 desde la parte inferior.

# 5 - Inserte el número de serie del 10 al 1

Código:

 Sub Ten_To_One () Dim i Como entero Dim j Como entero j = 10 Para i = 1 a 10 Rango ("A" & i) .Value = jj = j - 1 Siguiente i Fin 

Esto insertará números de serie del 10 al 1 desde la parte superior.

# 6 - Inserte hojas de trabajo tanto como desee

Código:

 Sub AddSheets () Dim ShtCount As Integer, i As Integer ShtCount = Application.InputBox ("¿Cuántas hojas le gustaría insertar?", "Agregar hojas",,,,,, 1) Si ShtCount = False, salga de Sub Else Para i = 1 a las hojas de trabajo ShtCount, agregue el siguiente i End If End Sub 

Esto le pedirá que ingrese la cantidad de hojas de trabajo que le gustaría insertar. Simplemente especifique el número en el cuadro de entrada y haga clic en Aceptar, insertará esas muchas hojas inmediatamente.

# 7 - Eliminar todas las hojas de trabajo en blanco del libro de trabajo

Código:

 Sub Delete_Blank_Sheets () Dim ws As Worksheet Application.DisplayAlerts = False Application.ScreenUpdating = False para cada ws en ActiveWorkbook.Worksheets If WorksheetFunction.CountA (ws.UsedRange) = 0 Entonces ws.Delete End If Next ws Application.DisplayAlerts = True Application .ScreenUpdating = True End Sub 

Esto eliminará todas las hojas de trabajo en blanco del libro en el que estamos trabajando.

# 8 - Insertar fila en blanco después de cada otra fila

Código:

 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) .Seleccione Siguiente i End Sub 

Para esto primero, debe seleccionar el rango donde le gustaría insertar filas en blanco alternativas.

# 9 - Resalte el error ortográfico

Código:

 Sub Chech_Spelling_Mistake () Atenuar MySelection como rango para cada MySelection en ActiveSheet.UsedRange si no es Application.CheckSpelling (Word: = MySelection.Text) Entonces MySelection.Interior.Color = vbRed End If Next MySelection End Sub 

Primero, seleccione los datos y ejecute el código VBA. Resaltará las celdas que tienen errores ortográficos.

# 10 - Cambiar todo a caracteres en mayúscula

Código:

 Sub Change_All_To_UPPER_Case () Dim Rng como rango para cada Rng en Selection.Cells If Rng.HasFormula = False Then Rng.Value = UCase (Rng.Value) End If Next Rng End Sub 

Primero, seleccione los datos y ejecute el código. Convertirá todos los valores de texto a caracteres en mayúsculas.

# 11 - Cambiar todo a minúsculas

Código:

 Sub Change_All_To_LOWER_Case () Dim Rng As Range For Cada 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