如何将单元格区域存储到variables中?

所以,我想对单元格范围做一个“更好的”引用,所以不需要将其复制/粘贴到我的方法中,但下面的代码不起作用:

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" 

您需要使用SetSet对象,如:Range:

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

正如Sid所build议的那样,您可能还需要澄清Cells部分,例如像这样。

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