如何将单元格范围存储到变量中?

时间:2013-02-08 14:35:34

标签: excel excel-vba excel-formula excel-2010 worksheet-function vba

所以,我想对单元格区域进行“更好”的引用,以便不必在整个方法中复制/粘贴它,但以下代码不起作用:

Dim cellRange As Range
' fieldIndex = 1, startRow = 10, lastRow = 20
cellRange = s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex))

我错过了什么?我可以在其他方面使用它就好了:

s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex)).Value = "bob"

2 个答案:

答案 0 :(得分:3)

您需要将Set用于范围:

等对象
Dim cellRange As Range
' fieldIndex = 1, startRow = 10, lastRow = 20
Set cellRange = s.Range(Cells(startRow, fieldIndex), Cells(lastRow, fieldIndex))

答案 1 :(得分:2)

正如Sid所建议的,您可能还需要澄清细胞部分,例如这样。

With s
   Dim cellRange As Range
   ' fieldIndex = 1, startRow = 10, lastRow = 20
   Set cellRange = .Range(.Cells(startRow, fieldIndex), .Cells(lastRow, fieldIndex))
End with