如何编写“步进”值的代码?

时间:2018-08-29 05:19:11

标签: excel vba excel-vba

我刚刚开始在Excel VBA中编程,并且有一个问题。

如何编写一个“步进”值的代码?

我只想使用do untildo whilefor对此进行编码。

我正在使用两个变量:x = 1y = 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

3 个答案:

答案 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