How to execute a VBA command on a sheet with a specific name?

Asked

Viewed 415 times

1

I have an Excel document with several sheets. In this document I need to execute a command on a specific sheet, that is by the sheet name. But if that sheet does not exist execute another command on another sheet with specific name until the sheets are finished.

Example:

Sub adicionar_categorias()

folhas = Array ("FOLHA 1", "FOLHA 2", "FOLHA 3")

For i = LBound(folhas) To UBound(folhas)
Worksheets(folhas(i)).Activate

Range("X2").Select
ActiveCell.FormulaR1C1 = "Computadores>Portáteis"
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("X2").AutoFill Destination:=Range("X2:X" & Lastrow)

Next i
End Sub

If the sheet is not in the book will give error Worksheets(sheets(i)). Activate! How to resolve the error?

RESOLVED: On Error Resume Next

Sub adicionar_categorias()

folhas = Array ("FOLHA 1", "FOLHA 2", "FOLHA 3")
On Error Resume Next
For i = LBound(folhas) To UBound(folhas)
Worksheets(folhas(i)).Activate

Range("X2").Select
ActiveCell.FormulaR1C1 = "Computadores>Portáteis"
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("X2").AutoFill Destination:=Range("X2:X" & Lastrow)

Next i
End Sub

Thank you "dot. Py!

1 answer

0


According to the documentation, can call the method .Activate, which is equivalent to clicking on the spreadsheet tab named as "Plan1" in your workbook.

Worksheets("Plan1").Activate

Instead of referencing by name, you can reference the position of the tab in your workbook, for example:

Worksheets(0).Activate
Worksheets(1).Activate
Worksheets(2).Activate

Where in a newly created workbook, the Worksheets(0) is equivalent to Plan1, to Worksheets(1) à Plan2 and the Worksheets(2) à Plan3.

Remembering that if you change the order of the tabs manually, although the name does not change, the position will change...


You can also create a array with the names of the worksheets you want to activate, and run a for for each item within that array.

planilhas = ("plan1", "plan2", "plan3", "plan4")

For i = 1 to UBound(planilhas)
    Worksheets(planilhas(i)).Activate
Next i

To improve this code, you can engage a try/catch/finally or a On Error Resume Next p/ that the program knows what to do when the tab exists, and what to do when not.

  • Thank you for your comment dot. Py!

  • Yes, but what if the sheet doesn’t exist. How do I fix the error and continue the loop?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.