我有我认为是一个非常基本的VBA挑战,并且花了几个小时来寻找答案。谢谢,如果有人可以将我指向正确的位置。
i具有B1 C1 = D1的公式,并且具有两个1x5矩阵的数据输入矩阵,一个用于Cell B1,一个用于单元格C1,例如[1,2,3,4,5]和[a,[a,B,C,D,E]分别在细胞(B2:B7)和(C2:C7)中。我想循环通过输入,以便我得到五个独特的答案[1 a,2 b,3 c,4 d,5 e],并在相邻的1x5矩阵中输出这些答案,细胞(D2:D7)。
记录宏不起作用,因为它记录了一个副本/粘贴操作,该操作不灵活地用于将来使用(用于扩展的矩阵,其他表格位置,更复杂的公式等)。
任何帮助。
亨利
更新:我相信我需要使用" do"或一些类似的循环代码,以及其他"one_answers"下一个"编码。
更新:这是我尝试使用代码的逐步图片:逐步过程结果图像
这是解决方案代码:
sub IterationMacro()
'声明变量
Dim h, i, j, k As Integer
Dim mySheet As Worksheet
Dim myAnswer As String
'设置工作表
Set mySheet = ActiveSheet
'迭代#套件
h = Range("B2").Value
'清除以前的内容
Range("C4:D4").ClearContents
Range("e5:e11").ClearContents
'通过循环运行
For i = 5 To h + 4
For j = 3 To 4
mySheet.Cells(4, j).Value = mySheet.Cells(i, j).Value
Next
'计算工作簿
Calculate
mySheet.Cells(i, 5).Value = mySheet.Cells(4, 5).Value
Next
结束sub
如果您可以绘制表或用作示例的内容,它可能会有所帮助。
假设我要降低您,您想在D1中使用公式,然后填充D7,从而在每一行中显示B C = D:
Range("D1").Formula="=B1+C1"
Range("D1:D7").Filldown
编辑:
在给出了示例图像之后,看起来您想在第2行(第1行中的标题)中进行数学。在第2行中,您想从" i"行中拔出值,然后在第2行中添加它们,然后粘贴该总和" i"中的答案。
Dim i as Integer 'i is the variable for the loop
For i = 3 to 9 'based on the picture, 3 to 9 are the 1 through 7 values
Cells(2,1).Value=Cells(i,1).Value 'pulls up Column A value from the loop to Row 2
Cells(2,2).Value=Cells(i,2).Value 'pulls up Column B value from the loop to Row 2
Cells(2,3).Formula="=A2+B2" 'Sums A2 and B2 into C2
Cells(2,3).Copy Cells(i,3) 'Copies the summed value to Row "i" in Column C
Next i 'Moves to next "i" in the loop
让我知道这是否更重要。
编辑:
动态范围,您仍然知道您的起点。您会查看类似的东西:
Dim i as Integer
Dim LR as Long
Dim LC as Long
LR=Cells(Rows.Count,"A").End(xlUp).Row
LC=Cells(1,Columns.Count).End(xlToLeft).Column
For i = 3 to LR 'Still starting at 3, because of the example
Cells(2,1).Value=Cells(i,1).Value
Cells(2,2).Value=Cells(i,2).Value
Cells(2,LC+1).Formula="=A2+B2" 'Note the LC+1 goes one row BEYOND the last column
Cells(2,3).Copy Cells(i,LC+1)
Next i
在最后一个示例中,您可以看到动态范围的语法。请注意,LR和LC是在循环外定义的,在子例程的持续时间内不会更改。