0

I would like to set a range to fit width columns, but I would like to set using numbers, no letters, something like this:

myWorksheet.Range(Cells(1, 1), Cells(1, 13)).Columns.AutoFit

But I get an error 400.

If I use

myWorksheet.Range("A1:M1").Columns.AutoFit

It works perfecly.

How I could to use cells to set the range and to do the AutoFit? Because I am using variables to set the range and I can't use letters, I have to use the numbers.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

3 Answers3

1

Try, please:

myWorksheet.Range(myWorksheet.Cells(1, 1), myWorksheet.Cells(1, 13)).EntireColumn.AutoFit

If your active worksheet is not myWorksheet, the ranges will belong to the active sheet. Then, EntireColumn ca be Autofit, not a cells range...

FaneDuru
  • 38,298
  • 4
  • 19
  • 27
1

You could use:

Sub test()
  
    With ThisWorkbook.Worksheets("myWorksheet")
    
        .Range(.Cells(1, 1), .Cells(1, 13)).EntireColumn.AutoFit
        
    End With

End Sub
Error 1004
  • 7,877
  • 3
  • 23
  • 46
0

you have to define cells in range..

you can try this

Dim Rg1 As Range
Dim Rg2 As Range

    Set Rg1 = Cells(1, 1)
    Set Rg2 = Cells(1, 13)

    Range(Rg1, Rg2).EntireColumn.AutoFit