我刚刚开始在Excel VBA中编程,并且有一个问题。
如何编写一个“步进”值的代码?
我只想使用do until
,do while
和for
对此进行编码。
我正在使用两个变量:x = 1
和y = 1
。该值必须是循环数。
输出看起来像这样:
cells(x,y). value = a
cells(2x,y). value = 2a
cells(2x,2y). value = 3a
cells(3x,2y). value = 4a
cells(3x,3y). value = 5a
cells(4x,3y). value = 6a
cells(4x,4y). value = 7a
答案 0 :(得分:1)
您可以使用以下数组在VBA中逐步浏览序列:
Sub StepAXY()
Dim Z As Long, A As Long, X As Long, Y As Long
Dim arrA() As Variant, arrX() As Variant, arrY() As Variant
arrA = Array(1, 2, 3, 4, 5, 6, 7)
arrX = Array(1, 2, 2, 3, 3, 4, 4)
arrY = Array(1, 1, 2, 2, 3, 3, 4)
For Z = 1 To 7 Step 1
A = arrA(Z - 1)
X = arrX(Z - 1)
Y = arrY(Z - 1)
Cells(X * 1, Y * 1) = A * 1
Next Z
End Sub
答案 1 :(得分:1)
这是另一种方法。这样会给您额外的一行(5x,4y),因此如果不需要,可以使用If语句排除。
Sub Generate()
Dim x As Long, y As Long, a As Long, b As Long, c As Long
For b = 1 To 4
Cells(b * x, b * y) = (2 * b - 1) * a
Cells((b + 1) * x, b * y) = 2 * b * a
Next b
End Sub
答案 2 :(得分:1)
这将是替代版本
Option Explicit
Public Sub Generate()
Dim a As Long: a = 1
Dim i As Long
For i = 1 To 7
Cells((i \ 2) + 1, ((i - 1) \ 2) + 1).Value = i * a
Next i
End Sub
请注意,这使用的不是标准分区5 \ 2
的{{3}} 5 / 2
。 div运算符将两个数字相除并返回整数结果。
5 / 2 = 2.5
的标准划分5 / 2 = 2
的除法运算符所以(i \ 2) + 1, ((i - 1) \ 2) + 1
会导致
1, 1
2, 1
2, 2
3, 2
3, 3
4, 3
4, 4