Excel VBA将公式粘贴到variables范围

我正在尝试创build一个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 [工作表捕获]

在此先感谢您的帮助

[1]:https://i.stack.imgur.com/xG6YN.png

很难说出自己没有提供多less信息,因此您的代码出现了哪些错误/问题。 无论哪种方式,我会刺激你调整你提供的做什么,我想你想做的事情:

 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 aj 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 

很明显,代码正在工作的前提是列和行variables正在返回期望值。