如何在不同的工作表中使用变量范围

时间:2015-03-05 17:14:19

标签: excel vba excel-vba variables range

我为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")

2 个答案:

答案 0 :(得分:1)

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

如果你只是使用Cell,那么它将引用活动表,而不是Sheet4。

从未使用RangeCells而没有特定的工作表限定符,这是一种很好的做法。您的代码不应该依赖于任何特定的活动表。

答案 1 :(得分:0)

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