循环通过工作表中的Excel VBA范围对象错误

时间:2015-02-04 13:49:34

标签: excel vba excel-vba

我正在尝试遍历工作簿中的不同工作表。我已经尝试搜索stackoverflow但仍然坚持错误。错误显示“object'_Worksheet'的”方法'范围'失败。

此代码的目的是标准化工作表中的所有格式。

Sub formatting()
Dim ws as Worksheet
Dim lastRow as long, lastColumn as long

lastRow = Range("A" & Rows.Count).End(xlUp).Row
lastColumn = (Cells(1, Columns.Count).End(xlToLeft).Column)

For each ws in Activeworkbook.Worksheets
With ws.Range(cells(lastRow, 1), cells(1, lastColumn))
    'rest of the actions I want to perform'
    .font.bold = true
End With
Next ws

End Sub

我刚开始使用Excel vba,请赐教!谢谢!

2 个答案:

答案 0 :(得分:0)

您必须符合Cells来电以及Range来电:

With ws.Range(ws.cells(lastRow, 1), ws.cells(1, lastColumn))

答案 1 :(得分:0)

如果您刚刚开始使用VBA,我将学习使用.currentregion设置范围,这将对您将来有很大帮助。

代码段使所有字段都变为粗体。如果您正在申请所有,那么currentregion可以在所有字段都连接的一个条件上保存代码和可能的错误。“

Sub formattingWithCurrentRegion()
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        ws.Range("A1").CurrentRegion.Font.Bold = True
    Next ws

End Sub

通过将区域设置为范围,您可以更好地控制范围以设置不同的格式,而无需处理循环中的循环。 见下文

Sub formattingWithCurrentRegion()
    Dim ws As Worksheet
    Dim rSheet As Range

    For Each ws In ActiveWorkbook.Worksheets
        '' sets the CurrentRegion as a range. Use the immediate window rSheet.Select to see what CurrentRegion does.
        Set rSheet = ws.Range("A1").CurrentRegion

        '' now you can work with it
        rSheet.Font.Bold = True

        '' make the 2 column font.color to Red
        rSheet.Resize(rSheet.Rows.Count, 1).Offset(0, 1).Font.Color = vbRed

        ''now clean up. Always set ranges to nothing when done with them.
        Set rSheet = Nothing
    Next ws

End Sub