Saltar al contenido principal

¿Cómo ejecutar la misma macro en varias hojas de trabajo al mismo tiempo en Excel?

Normalmente, podemos ejecutar una macro en una hoja de trabajo, si hay varias hojas que necesitan aplicar esta misma macro, debe activar el código una por una. ¿Existe alguna otra forma rápida de ejecutar la misma macro en varias hojas de trabajo a la vez en Excel?

Ejecute o ejecute la misma macro en varias hojas de trabajo al mismo tiempo con código VBA


Ejecute o ejecute la misma macro en varias hojas de trabajo al mismo tiempo con código VBA

Para ejecutar una macro en varias hojas al mismo tiempo sin activarla una por una, puede aplicar el siguiente código VBA, haga lo siguiente:

1. Mantenga pulsado el ALT + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. Hacer clic recuadro > Móduloy pegue la siguiente macro en el Módulo Ventana.

Código de VBA: ejecute la misma macro en varias hojas de trabajo al mismo tiempo:

Sub Dosomething()
    Dim xSh As Worksheet
    Application.ScreenUpdating = False
    For Each xSh In Worksheets
        xSh.Select
        Call RunCode
    Next
    Application.ScreenUpdating = True
End Sub
Sub RunCode()
    'your code here
End Sub

Note: En el código anterior, copie y pegue su propio código sin el Sub partida y End Sub pie de página entre el Sub Runcode () y End Sub guiones. Ver captura de pantalla:

doc ejecutar macro en todas las hojas 1

3. Luego coloque el cursor en la macro de la primera parte y presione F5 para ejecutar el código, y su código de macro se aplicará a una hoja por una.


Elimine todas las macros de varios libros de trabajo:

Kutools for Excel's Eliminar todas las macros por lotes La utilidad puede ayudarlo a eliminar todas las macros de varios libros de trabajo según lo necesite. ¡Descarga y prueba gratis Kutools para Excel ahora!

doc ejecutar macro si la celda cambia 3

Kutools for Excel: con más de 300 prácticos complementos de Excel, prueba gratuita y sin límite en 30 días. ¡Descarga y prueba gratis ahora!

Las mejores herramientas de productividad de oficina

🤖 Asistente de IA de Kutools: Revolucionar el análisis de datos basado en: Ejecución inteligente   |  Generar codigo  |  Crear fórmulas personalizadas  |  Analizar datos y generar gráficos  |  Invocar funciones de Kutools...
Características populares: Buscar, resaltar o identificar duplicados   |  Eliminar filas en blanco   |  Combine columnas o celdas sin perder datos   |   Ronda sin fórmula ...
Super búsqueda: Búsqueda virtual de criterios múltiples    Búsqueda V de valores múltiples  |   VLookup en varias hojas   |   Búsqueda difusa ....
Lista desplegable avanzada: Crear rápidamente una lista desplegable   |  Lista desplegable dependiente   |  Lista desplegable de selección múltiple ....
Administrador de columnas: Agregar un número específico de columnas  |  Mover columnas  |  Toggle Estado de visibilidad de columnas ocultas  |  Comparar rangos y columnas ...
Características destacadas: Enfoque de cuadrícula   |  Vista de diseño   |   Gran barra de fórmulas    Administrador de hojas y libros de trabajo   |  Biblioteca de Recursos (Texto automático)   |  Selector de fechas   |  Combinar hojas de trabajo   |  Cifrar/descifrar celdas    Enviar correos electrónicos por lista   |  Súper filtro   |   Filtro especial (filtro negrita/cursiva/tachado...) ...
Los 15 mejores conjuntos de herramientas12 Texto Herramientas (Añadir texto, Quitar caracteres, ...)   |   50+ Tabla Tipos (Diagrama de Gantt, ...)   |   40+ Práctico Fórmulas (Calcular la edad según el cumpleaños, ...)   |   19 Inserción Herramientas (Insertar código QR, Insertar imagen desde la ruta, ...)   |   12 Conversión Herramientas (Números a palabras, Conversión de Moneda, ...)   |   7 Fusionar y dividir Herramientas (Filas combinadas avanzadas, Células partidas, ...)   |   ... y más

Mejore sus habilidades de Excel con Kutools for Excel y experimente la eficiencia como nunca antes. Kutools for Excel ofrece más de 300 funciones avanzadas para aumentar la productividad y ahorrar tiempo.  Haga clic aquí para obtener la función que más necesita...

Descripción


Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
Comments (16)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
The original macro "How to run the same macro on multiple worksheets at same time in Excel" is fantastic for my purposes, thanks so much. I was wondering if there's a way to get it to return to the first worksheet where I have a control to run the macro. Currently it goes through 25 worksheets doing my code (autofit & Sort by date) and stops once it's done the last worksheet of the 25. Returning to the first sheet would be the icing on the cake! Thanks in advance for thinking about this.
This comment was minimized by the moderator on the site
is there a way to only do it on selected worksheets and not all?
This comment was minimized by the moderator on the site
Hello, karen,
To run the code on selected sheet, please apply the below code:
Step1: Copy anf paste the below code into the Module Window
'Replace this code with your own, but keep the script inside the parentheses
Sub LCase(ws As Worksheet)
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
For Each Rng In WorkRng
    Rng.Value = VBA.LCase(Rng.Value)
Next
End Sub

Sub RunOnSelectedSheets()
    Dim ws As Worksheet
    For Each ws In ActiveWindow.SelectedSheets
        LCase ws    'change the LCase code name to your own code name
    Next ws
End Sub



Step2: Replace the first section of code above with your own code, but keep the script inside the parentheses. And change the LCase code name to your own code name.

Step3: Then, select the worksheet you want to run this code.
After running the code, your code will be executed on each of the selected sheets.

Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Terimakasih sebelumnya atas ilmu ilmu yg sudah di share. Saya sudah memakai beberapa VBA anda.

Tapi bolehkan saya meminta tolong untul mencarikan VBA yg tepat untuk mengaktifkan VBA yg sudah ada di sheet tertentu tanpa harus masuk ke sheet tersebut.

Contohnya.
Saya sudah menggunakan vBA anda yg berfungsi untuk mengurutkan data secara otomatis.

Tetapi ketika data yg saya terapkan itu berubah karena hasil pencarian data dari sheet yg berbeda. vBA tersebut tidak aktif. Harus terlebih dahulu masuk ke Sheet Tersebut untuk merubah data dengan manual barulah VBa pengurutan dat tersebut aktif.

Bisakah dicarikan VBA nya?
This comment was minimized by the moderator on the site
It works, but the current sheet is always running twice. The rest sheets are perfect and run only once!
This comment was minimized by the moderator on the site
Hello, hou,
May be you can use the below code to your need:
Sub WorksheetLoop()
         Dim Current As Worksheet
         For Each Current In Worksheets

          'Insert your code here.
           
      End Sub


Note: In the above code, please copy and paste your own code without the Sub heading and End Sub footer.

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Thank you so much! But it's not working. It only runs the current sheet for several times.
This comment was minimized by the moderator on the site
How do you exclude certain sheets and add On Error Resume Next? Thanks in advance
This comment was minimized by the moderator on the site
Before xSh.selectyou have to activate
So,xSh.activatexSh.select
This comment was minimized by the moderator on the site
The code "Run the same macro on multiple worksheets at same time" works perfectly, Thanks !

However I have this error at "xSh.Select" and I don't know why...there is no issue visible in the sheets... AND I don't have any hidden sheets.

The error is '1004': Method'Select' of object '_Worksheet' failed


Thanks in advance for your help
This comment was minimized by the moderator on the site
For those wiFor those with 1004 runtime error, verify you don´t have any hidden sheets. If you do, unhide them. Then this code snippet works. Greetings.th 1004 runtime error, verify you don´t have any hidden sheets. If you do, unhide them. Then this code snippet works. Greetings.
This comment was minimized by the moderator on the site
Is there a way to make this run only on unhidden sheets? I need this code to run only on visible sheets.
This comment was minimized by the moderator on the site
or
On Error Resume Next

'above

xSh.Select

This comment was minimized by the moderator on the site
1004 runtime error
This comment was minimized by the moderator on the site
Sub Dosomething()
Dim xSh As Worksheet
Application.ScreenUpdating = False
For Each xSh In Worksheets
xSh.Select
Call RunCode
Next
Application.ScreenUpdating = True
End Sub
Sub RunCode()
With Worksheets("2018")
.EnableOutlining = True
.EnableSelection = xlNoRestrictions
.Protect Password:="workana1234", _
Contents:=True, UserInterfaceOnly:=True
End With
End Sub


Hola! he seguido las pautras pero me señala como error la fila xSh.Select.

Al dar F5 me indica que se ha producido un error 1004 en tiempo de ejecucion.

Error en el metodo "Select" de Objeto "_Worksheet"



Help!!!!
This comment was minimized by the moderator on the site
On Error Resume Next
above
xSh.Select
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations