在更改行宽和列高

时间:2017-04-24 10:23:27

标签: excel-vba vba excel

我有一个代码可以从第1行和第B列更改工作簿中所有工作表的行高和列宽。 我的问题是它使我所有隐藏的列和行也可见。 请建议我如何修改代码,以便它可以更改列宽和行高,但应该将它们隐藏起来。

Sub rowcolallsheetb()
  Dim exworkb As Workbook
  Dim xlwksht As Worksheet
  Dim lastrow1 As Long
  Dim lastcolumn1 As Long
  Dim firstrowDB As Long
  Dim Z As Integer

  Dim ShtNames() As String
  ReDim ShtNames(1 To ActiveWorkbook.Sheets.Count)
  For Z = 1 To Sheets.Count
    ShtNames(Z) = Sheets(Z).Name
    Sheets(Z).Select
    lastrow1 = Sheets(Z).Cells(Rows.Count, "A").End(xlUp).Row
    lastcolumn1 = Sheets(Z).Cells(1, Columns.Count).End(xlToLeft).Column
    ActiveWorkbook.Sheets(Z).Range(Sheets(Z).Cells(1, 2), Sheets(Z).Cells(lastrow1, lastcolumn1)).Select
    Selection.Cells.RowHeight = 9.4
    Selection.Cells.ColumnWidth = 11.2
  Next Z
End Sub

1 个答案:

答案 0 :(得分:2)

使用SpecialCells(xlCellTypeVisible)从您的操作中排除隐藏的单元格:

With ActiveWorkbook.Sheets(Z).Range("B1", Sheets(Z).Cells(lastrow1, lastcolumn1)) _
    .SpecialCells(xlCellTypeVisible)
'   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    .ColumnWidth = 11.2
    .RowHeight = 9.4
End With

您也可以使用

              'vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
With Selection.SpecialCells(xlCellTypeVisible)
    .ColumnWidth = 11.2
    .RowHeight = 9.4
End With

但始终建议不要在VBA中使用Select内容。