【问题标题】:Excel VBA to Paste Formula to Variable RangeExcel VBA 将公式粘贴到变量范围
【发布时间】:2017-03-23 19:21:13
【问题描述】:

我正在尝试创建一个 VBA 代码,它将公式粘贴到列和单元格的可变范围。我有一个我认为可以修改的代码的开头,但我没有成功。

我有一张纸(见图),其范围在 A2 和 ?我需要将一个公式粘贴到区域 C3 到行和列的末尾,该公式将取 B 中的值并将其除以列数。我以为我有一个开始,但我失败了。

请帮忙。 “开始”代码如下

Sub QtyByWks()
    Dim M As Long, N As Long, i As Long, x As Long, j As Long
    M = Sheet10.Cells(1, Columns.count).End(xlToLeft).Column
    N = Sheet10.Cells(Rows.count, "A").End(xlUp).Row
    j = 3
    For x = 1 To M
        For i = 1 To N
            If Cells(i, "B").Value > 0 Then
                Cells(j, "C").Value = Cells(i, "B").Value
                j = j + 2
            End If
        Next i
    Next x
End Sub

另请注意,行和列都可以通过额外的 VBA [捕获工作表] 进行更改

提前感谢您的帮助

【问题讨论】:

  • 我收到一条提醒说要在审核后发布图片?
  • 您能举例说明您的预期结果吗?

标签: vba excel


【解决方案1】:

由于您没有提供太多信息,因此很难说出您的代码有哪些错误/问题。无论哪种方式,我都会尝试调整您提供的内容以执行我认为您正在尝试执行的操作:

Sub QtyByWks()
    Dim M As Long, N As Long, i As Long, x As Long, j As Long
' Changed the formula to check row 2 instead of one, as per your screenshot.
    M = Sheet1.Cells(2, Columns.count).End(xlToLeft).Column
    N = Sheet1.Cells(Rows.count, "A").End(xlUp).Row
    j = 3
'Replaced the x loop with a j loop that increments by 2.  
    For j = 3 To N Step 2
'Had the i loop start from 3 instead of 1
        For i = 3 To M
            If Cells(j, "B").Value > 0 Then
'Divided the "B" value by the number of columns M, which is what it sounds like you were going for in your description.
                Cells(j, i).Value = Cells(j, "B").Value / (M - 2)
            End If
        Next i
    Next j
End Sub

显然,代码是在假设 Columns 和 Rows 变量返回预期值的情况下工作的。

【讨论】:

  • 完美!我以为我的问题很清楚,对不起。但是你搞定了。如果你愿意,请帮帮我?为什么“j”循环与“x”循环?为什么从 3 对 1 开始“i”循环?
  • 您没有在任何地方使用 x。您将 j 用于行,而 i 用于...嗯,很难说。但是 x 并没有在任何地方使用。然后,我将 i 循环设置为从 3 开始并转到 M,因为这是您要填充的列范围,介于 C(第 3 列)和 M 之间。如果我们从 i = 1 开始,您将覆盖A 列和 B 列。
猜你喜欢
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多