对于单个单元格更容易:使用默认的 Cells() 函数:
Cells(1,1) = "hello world"
或使用工作表的 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
说明:
Cells 函数接收:
字符串参数 - 在其中指定 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))"