简体   繁体   English

Excel VBA:用数组替换第一行

[英]Excel VBA: Replace first row by an array

I have a first row with 100 cells and I created an Array of Strings, which represent the new row content. 我有第一行包含100个单元格,并创建了一个字符串数组,代表新的行内容。 I would like to replace the content of all the first row with the content of my Array in VBA, how can I do that? 我想用VBA中我的数组的内容替换所有第一行的内容,我该怎么做?

Say your array is called myArray , it's enough to do this: 假设您的数组名为myArray ,则足以完成此操作:

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

The functions LBound() and UBound() are respectively returning the first and the last index of your array. 函数LBound()UBound()分别返回数组的第一个索引和最后一个索引。

Please note that when writing Cells(1,j+1) I'm assuming two important things: 请注意,在编写Cells(1,j+1)我假设有两个重要事项:

1) Your start index starts with 0, so I want to start the insertion of the values from the column 1 (j+1 = 0+1 = 1). 1)您的起始索引从0开始,所以我想从列1(j + 1 = 0 + 1 = 1)开始插入值。

2) You want to override the first row (because the row index is equal to 1). 2)您想覆盖第一行(因为行索引等于1)。

You might want to customize this, for example creating independent indexes - when I say "independent", I mean "not depending on the lower and the upper bound of your array, nor being hard-coded like I did for the "row 1". 您可能想要自定义此内容,例如创建独立索引-当我说“独立”时,我的意思是“不依赖于数组的上下限,也不像我对“行1”那样进行硬编码。

You can read and write between a Range and an Array in one line. 您可以在一行中在范围和数组之间进行读取和写入。 It is more efficient than using a loop. 它比使用循环更有效。

Note: The array must be 2 Dimensional to write to a range. 注意:数组必须是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM