【问题标题】:how to use variable ranges in different sheets如何在不同的工作表中使用变量范围
【发布时间】:2015-03-05 17:14:19
【问题描述】:

我为 2 个范围内的产品编写了代码。其中一个范围在其他范围内,当我试图使其可变时,出现了一些错误。这是代码:

Sub Correlacionar()

Dim col As Integer
Dim random As Range
Dim SDesv As Range
Dim Chole As Range
col = 4

Set Chole = Sheet4.Range("a20:d23")
'Set Chole = Sheet4.Range(Cells(20, 1), Cells(19 + col, col))

Set random = Range(Cells(3, 9), Cells(3, 8 + col))
Set SDesv = Range(Cells(10, 1), Cells(10, col))
SDesv = WorksheetFunction.MMult(random, WorksheetFunction.Transpose(Chole))
Application.CutCopyMode = False
End Sub

我想使用:

Set Chole = Sheet4.Range(Cells(20, 1), Cells(19 + col, col))

代替:

Set Chole = Sheet4.Range("a20:d23")

【问题讨论】:

  • 您收到的错误是什么?也许您可以在问题中添加一些示例数据。

标签: vba excel variables range


【解决方案1】:
Set Chole = Sheet4.Range(Sheet4.Cells(20, 1), _
                         Sheet4.Cells(19 + col, col))

如果您只使用单元格,那么它将引用活动表,而不是 Sheet4。

最好从不在没有特定工作表限定符的情况下使用Range 或Cells。您的代码不应依赖于任何处于活动状态的特定工作表。

【讨论】:

    【解决方案2】:

    类似于Can't work with ranges if workbook and sheet are not active

    Cells 隐式引用 ActiveSheet.Cells

    with sheet4
       set Chole = .range(.cells(20,1), cells(19 + cells(19 + col, col))
    end with
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多