【问题标题】:Excel VBA: Replace first row by an arrayExcel VBA:用数组替换第一行
【发布时间】:2015-03-18 13:23:33
【问题描述】:

我有一个包含 100 个单元格的第一行,我创建了一个字符串数组,它代表新的行内容。 我想用 VBA 中我的 Array 的内容替换所有第一行的内容,我该怎么做?

【问题讨论】:

    标签: arrays excel vba replace


    【解决方案1】:

    假设你的数组被称为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)。

    您可能想要自定义它,例如创建独立索引 - 当我说“独立”时,我的意思是“不依赖于数组的下限和上限,也不会像我为“第 1 行”。

    【讨论】:

      【解决方案2】:

      您可以在一行中在 Range 和 Array 之间进行读写。它比使用循环更有效。

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

      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
      

      【讨论】:

        猜你喜欢
        • 2015-05-23
        • 1970-01-01
        • 2015-05-22
        • 1970-01-01
        • 2016-05-09
        • 2019-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多