[英]Excel VBA to Paste Formula to Variable Range
I am attempting to create a VBA code that will paste a formula to Variable Range of both columns and cells. 我正在尝试创建一个VBA代码,将公式粘贴到列和单元格的可变范围。 I have the start of a code I thought I could modify, but I have been unsuccessful. 我有一个我认为可以修改的代码的开头,但是我没有成功。
I have a sheet (see image) that has a variable range between A2 & ? 我有一张工作表(见图),其范围在A2和?之间。 I need to paste into the area C3 to the end of rows and columns a formula that will take the value in B and divide it by the number of columns. 我需要将区域C3粘贴到行和列的末尾,这个公式将采用B中的值并将其除以列数。 I thought I had a start but I am failing. 我以为我有一个开始,但我失败了。
Please assist. 请协助。 "Start" Code Follows “开始”代码遵循
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
Also note, Both Rows and Columns are Variable via an additional VBA [Capture of Worksheet] 另请注意,“行”和“列”都可通过其他VBA进行变量[工作表捕获]
Thanks in advance for the assist 在此先感谢您的帮助
Hard to tell what sort of errors/issues you had with your code since you haven't provided much info. 很难说你的代码有什么样的错误/问题,因为你没有提供太多的信息。 Either way, I'll take a stab at adjusting what you provided to do what I THINK you're trying to do: 无论哪种方式,我都会尝试调整你提供的内容来做我认为你想要做的事情:
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
Obviously the code is working on the assumption that the Columns and Rows variables are returning expected values. 显然,代码正在假设Columns和Rows变量返回预期值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.