2013-07-14 106 views
6

为什么下面不工作: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

完全糊涂了。

回答

2

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

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

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

这是为什么我不知道,但... –

+0

这只是混乱,因为它违背了自己的文档,只要我可以电话(说你必须使用A1风格作为第一个参数)。我想这只是你必须忍受的那些奇怪的设计决定之一。 – user943870

+0

并非如此,如果向下滚动文档,将会看到如果使用“单元格”属性,会出现不同的条件......在该部分中,实际上并没有提及A1样式(显然它与单元格属性有关)。 –

12

Range与单个参数时,该参数被解释为区域名称。

Range(Cells(1,1)) 

是一样的使用

Range(Cells(1,1).Value) 

所以,你将得到的结果只有通过了两项范围内参数仅当是Cells(1,1)值在A1风格

的有效范围地址他们解释为一个范围的角落。

+0

+1好帖子Chris。 – brettdj

+0

不错,但可以更完整的单元格(1,1)。地址示例? – LuizAngioletti

+1

Range(Cells(1,1).Value)在我的机器上引发错误。范围(Cells(1,1).Address)虽然工作。 – user3032689

-2

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

+0

了解更多吗? – tod

3

而是指这样的单细胞:

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

你可以写:

Range(Cells(1,1).Address) 
1

对于单个细胞中的多简单:使用默认的单元格()函数:

Cells(1,1) = "hello world" 

,或者使用一个表的单元格()函数:

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 

说明:

细胞功能接收任一:
一个字符串参数 - 在其中指定的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))"