如何使用不同的变量自动填充 VBA 中的范围

How to autofill a range in VBA with differing variables

我想弄清楚如何根据同一行中已定义的数据自动填充特定范围的单元格。我的任务更复杂,但可以在下面的代码中看到步骤的简化。我想要实现的是:

  1. 定义我想要输出值的范围
  2. 将所选范围单元格(左侧)同一行中的两个值相乘,并在当前所选范围单元格中输出该数字。为此,要相乘的数字之一将取决于行中的字符串(描述其类型)。
  3. 遍历定义的范围并对每一行重复计算。

我当前的代码如下,输出“应用程序定义或对象定义错误”。

如有任何帮助,我们将不胜感激。

For a = Range("P12") To Range("P33") 'Range of cells I want to fill.
    If Cells(a, -10).Value = "B" 'If the cell 10 to the left of our "a" value is = "B".
    Then c = Cells(a, -10).Value * Worksheets("LCI").Range("D4").Value 'Then new variable "c" = (cell 9 to left of a) * (number from another sheet containing a database)
            
    Cells(a).Value = c 'Update value of selected range cell to contain c which we calculated.
Next 'Repeat for all rows in range.

你很接近。

  1. 您需要将 a 视为单元格或 Range 对象。该变量是单元格本身,它具有 a.rowa.column 等属性,这些属性描述了它在它所在的 sheet 上的位置。 当您说 Cells(a, -10) 时,您说的是 “在 Activesheet 上,我想要一个单元格,其中行为 a,列的编号为 -10。没有行 a(因为 a 是一个 range/cell 对象,并且因为您没有在此处指定您想要 a 中的哪个 属性 它将默认到 a.value,这可能什么都没有)并且 Activesheet.

    上没有列 -10
  2. 你的循环定义不正确。您可以使用 For Each 循环遍历范围内的单元格。

改为:

For Each a In Range("P12:P33")
    'clear `c` each loop 
    c=0
    If a.Offset(,-10).Value = "B" Then 'start at cell `a` and move back 10 columns and grab the value
        c = a.Offset(, -10).Value * Worksheets("LCI").Range("D4").Value
    End If
    a.Value = c
Next a