Excel VBA:用数组replace第一行

我有100个单元格的第一行,我创build了一个string数组,表示新的行内容。 我想用VBA中的数组内容replace所有第一行的内容,我该怎么做?

说你的数组被称为myArray ,这足以做到这一点:

 For j = LBound(myArray) To UBound(myArray) Sheets("your sheet").Cells(1,j+1).Value = myArray(j) Next j 

函数LBound()UBound()分别返回数组的第一个和最后一个索引。

请注意,在写Cells(1,j+1)我假设两件重要的事情:

1)你的起始索引从0开始,所以我想开始插入列1(j + 1 = 0 + 1 = 1)的值。

2)你想覆盖第一行(因为行索引等于1)。

你可能想要定制这个,例如创build独立索引 – 当我说“独立”时,我的意思是“不依赖于数组的下限和上限,也不像我为”第1行“那样进行硬编码。

您可以在一行中读取和写入范围和数组之间。 这比使用循环更有效率。

注意:数组必须是2维才能写入范围。

 Public Sub ReadToArray() ' Create dynamic array Dim StudentMarks() As Variant ' Read values into array from 100 cells in row 1 StudentMarks = Sheets("Sheet1").Range("A1:CV1").Value ' Do something with array ' Write the values back to sheet Sheets("Sheet1").Range("A1:CV1").Value = StudentMarks End Sub