Excel VBA - How to select colums in a specific sheet?

12,860

I tested your code and it works fine as follows.

Sub test()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Mysheet")
    ws.Columns("A:S").EntireColumn.AutoFit
End Sub

No need to Select anything, so I put the two statements together without the Select.

I added ThisWorkbook to (more) fully qualify your ws declaration. Make sure the worksheet Mysheet is in ThisWorkbook otherwise change that to state which workbook the sheet resides in.

Share:
12,860
Totallama
Author by

Totallama

Updated on June 08, 2022

Comments

  • Totallama
    Totallama almost 2 years

    I need to select columns on a specific sheet. Somehow this is not working:

    Dim ws As Worksheet
    Set ws = Worksheets("Mysheet")
    ws.Columns("A:S").Select
    Selection.EntireColumn.AutoFit
    

    And simple Columns("A:S").Selectdoesn't activate the sheet I need