使用范围(单元格,单元格)在VBA中的范围错误设置范围

时间:2016-06-07 17:20:25

标签: vba excel-vba excel

我正在重新编写旧工作表中的代码以更新它并使其更有效。

我有一个格式化数据表的子程序,但我收到一个错误,我不知道为什么我会得到一个。我的VBA有点生疏,但以下代码应该正常工作

Sub FormatPnLDataTable(tableRange As Range)
    Dim tempRange As Range, ws As Worksheet
    Dim lStartRow As Long, lEndRow As Long, lLastCol As Long

    Set ws = Sheets("PandLDataTable")
    Application.CutCopyMode = False
    lStartRow = tableRange.Row
    lEndRow = lStartRow + tableRange.Rows.Count
    lLastCol = tableRange.Columns.Count

    'format the whole table with border
    With tableRange
        'format borders
        'code removed for brevity
    End With
    'set range for the top row of table
    Set tempRange = ws.Range(Cells(lStartRow, 1), Cells(lStartRow, lLastCol))

代码在这一行犯了错误

 Set tempRange = ws.Range(Cells(lStartRow, 1), Cells(lStartRow, lLastCol))

但工作表(ws)有效,变量都有正确的值 对于此特定实例,lStartRow为1,lEndRow为15,lLastCol为35

1 个答案:

答案 0 :(得分:3)

Set tempRange = ws.Range(Cells(lStartRow, 1), Cells(lStartRow, lLastCol))

虽然您已使用ws来限定Range来电,但 会自动应用于Cells来电 - 这些模块默认情况下会引用ActiveSheet。

这将更加强大:

Set tempRange = ws.Range(ws.Cells(lStartRow, 1), ws.Cells(lStartRow, lLastCol))

另请参阅:What is the default scope of worksheets and cells and range?

相关问题