VBA Excel范围()与单元格参数

为什么以下不起作用:

Range(Cells(1,1)).Value = 3

Cells(1,1)应该基本上和使用A1东西一样吗?

(我意识到我可以做Cells(1,1).Value = 3 ,但我只是好奇它为什么不起作用。)

我读了MSDN条目,它显示第一个参数必须是A1风格,但是像这样的工作:

Range(Cells(1,1), Cells(2,3)).Value = 2

完全困惑。

当你想使用Cells属性来指定范围对象的参数(如果我没有记错的话 – 我有一段时间没有使用VBA),那么你必须有效地提供两个参数。

所以如果你想引用一个只有一个单元格的范围对象,那么你需要写:

 Range(Cells(1, 1), Cells(1, 1)).value = "Hello World" 

Range与单个参数一起使用时,该参数被解释为范围名称。

 Range(Cells(1,1)) 

和使用一样

 Range(Cells(1,1).Value) 

所以你只会得到一个结果是Cells(1,1)的值是A1样式中的有效范围地址

只有当传递两个范围参数,他们被解释为一个范围的angular落。

而不是像这样的单个单元格:

 Range(Cells(1,1), Cells(1,1)) 

你可以写:

  Range(Cells(1,1).Address) 

对于单个单元格来说更容易:使用默认的Cells()函数:

 Cells(1,1) = "hello world" 

或者使用Sheet的Cells()函数:

 Dim sht as Worksheet Set sht = Sheets("myworksheet") ' or: = Sheets(1) sht.Cells(1,1) = "hello world" 

对于一个范围,你将不得不使用两个参数,在这里给出的其他答案中解释。 但其优点是您可以将整个范围的字段设置为一个值。 在幕后,你可以在不是“主动”的工作表上工作。 例如:

 Const colRand = 4 Const colDiff = 5 Dim sht as Worksheet, rngHi As Range, rngRand As Range, rngDiff As Range Set sht = Sheets("myworksheet") ' or: = Sheets(1) Set rngHi = sht.Range(sht.Cells(1,1), sht.Cells(3,3) rngHi = "hello world" Set rngRand = sht.Range(sht.Cells(1,colRand), sht.Cells(8,colRand) ' column 4, rows 1-8 rngRand = "=RAND()" Set rngDiff = sht.Range(sht.Cells(2,colDiff), sht.Cells(8,colDiff) ' column 5, rows 2-8 ' using FormulaR1C1 in case the sheet isn't set to use that type of formula Set rngDiff.FormulaR1C1="=RC[-1] - R[-1]C[-1]" ' on previous columnn, diff between this row and previous row 

说明:

单元格function可以接收:
一个string参数 – 您可以在其中指定A1_And_Colon样式范围
两个单元格参数 – 范围的开始单元格和结束单元格。

所以要设置“单元格”的范围,你需要给这两个单元格用逗号分隔:

 Range(Cells(1,1), Cells(1,1)) = "hello world" Range(Cells(2,2), Cells(3,4)) = "you cannot square around, but you can round a square" Sheets(1).Cells(5,5) = "=Round(Sqrt(5))" 

当使用“单元格”时,需要制定Object.cells,例如Application.cells(2,2)或activeWorksheet.cells