每个工作表循环的 Excel VBA

标签 excel vba for-loop each worksheet

我正在编写代码,基本上浏览工作簿中的每张工作表,然后更新列宽。下面是我写的代码;我没有收到任何错误,但它实际上也没有做任何事情。非常感谢任何帮助!

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
Range("A:A").ColumnWidth = 20.14
Range("B:B").ColumnWidth = 9.71
Range("C:C").ColumnWidth = 35.86
Range("D:D").ColumnWidth = 30.57
Range("E:E").ColumnWidth = 23.57
Range("F:F").ColumnWidth = 21.43
Range("G:G").ColumnWidth = 18.43
Range("H:H").ColumnWidth = 23.86
Range("i:I").ColumnWidth = 27.43
Range("J:J").ColumnWidth = 36.71
Range("K:K").ColumnWidth = 30.29
Range("L:L").ColumnWidth = 31.14
Range("M:M").ColumnWidth = 31
Range("N:N").ColumnWidth = 41.14
Range("O:O").ColumnWidth = 33.86
End Sub

最佳答案

尝试稍微修改您的代码:

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call resizingColumns(ws)
    Next
End Sub

Sub resizingColumns(ws As Worksheet)
    With ws
        .Range("A:A").ColumnWidth = 20.14
        .Range("B:B").ColumnWidth = 9.71
        .Range("C:C").ColumnWidth = 35.86
        .Range("D:D").ColumnWidth = 30.57
        .Range("E:E").ColumnWidth = 23.57
        .Range("F:F").ColumnWidth = 21.43
        .Range("G:G").ColumnWidth = 18.43
        .Range("H:H").ColumnWidth = 23.86
        .Range("i:I").ColumnWidth = 27.43
        .Range("J:J").ColumnWidth = 36.71
        .Range("K:K").ColumnWidth = 30.29
        .Range("L:L").ColumnWidth = 31.14
        .Range("M:M").ColumnWidth = 31
        .Range("N:N").ColumnWidth = 41.14
        .Range("O:O").ColumnWidth = 33.86
    End With
End Sub

请注意,resizingColumns 例程采用参数 - 范围所属的工作表。

基本上,当您使用 Range("O:O") 时 - 代码以 ActiveSheet 的范围进行操作,这就是为什么您应该使用 With ws 语句,然后是 .Range("O:O")

并且不需要使用全局变量(除非您在其他地方使用它们)

关于每个工作表循环的 Excel VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21918166/

相关文章:

python使用for循环更新嵌套字典值与理解

vba - 将 VBA 数组打印到 Excel 单元格

ms-access - 如何 Access Access 中选定的行?

c# - 如何使用C#获取Excel中当前打开的文档?

python - 导入多索引数据而不创建整数列名称

ms-access - 自动递增字母到特定数字

c++ - 使用 for 循环创建条形图

python - 寻找 python 列表中点之间最短距离的更简洁方法?

Excel VBA 代码强制指定缩放级别

excel - 在 Excel 中使用 MS Query 查询自身(不是外部源)