首页 > 解决方案 > 设置列宽大小命令不循环遍历所有活动工作表

问题描述

下面的代码执行没有错误,除了下面的行没有在所有活动工作表中执行(可能是因为需要包含行?)。

Columns("T").ColumnWidth = 50

完整的宏是:

Sub Resize_Columns_And_Rows_No_Header2()

Dim currentSheet As Worksheet

Set currentSheet = ActiveSheet

Dim sheet As Worksheet

Columns("T").ColumnWidth = 50

For Each sheet In ActiveWorkbook.Worksheets
    With sheet

Columns("T").ColumnWidth = 50

With .Cells.Rows
            .WrapText = True
            .VerticalAlignment = xlCenter
            .EntireRow.AutoFit
        End With '.Cells.Rows
        .Columns.EntireColumn.AutoFit
    End With 'sheet
Next sheet

currentSheet.Activate

End Sub

标签: excelvba

解决方案


问题是Columns("T").ColumnWidth = 50With sheet需要以点开头的行,否则将不会在sheet.

因此,将其中的行更改With sheet为:

.Columns("T").ColumnWidth = 50

实际上,您不需要这些currentSheet东西,最终也不需要,currentSheet.Activate因为活动工作表永远不会更改运行以下代码:

Public Sub Resize_Columns_And_Rows_No_Header2()
    Dim sheet As Worksheet
    For Each sheet In ActiveWorkbook.Worksheets
        With sheet

            .Columns("T").ColumnWidth = 50

            With .Cells.Rows
                .WrapText = True
                .VerticalAlignment = xlCenter
                .EntireRow.AutoFit
            End With '.Cells.Rows

            .Columns.EntireColumn.AutoFit
        End With 'sheet
    Next sheet
End Sub

推荐阅读