使用双“For”循环标记区域

时间:2015-10-21 15:44:43

标签: excel vba for-loop

我正在尝试执行以下操作:我想在字符串中存储不同的区域(以黄色标记)。第一个黄色区域是F7:G8,第二个是I7:J8,依此类推,使得字符串变为:“F7:G8,I7:J8,L7:M8,F10:G11,I10:J11,L10:M11”。

enter image description here

所以在这个例子中,我有三个区域在右边,两个区域在下面。向右和向下的区域数量可能会有所不同,因此我想制作一个代码,我只需要指定向右和向下的区域数量。请注意,第一个区域始终为F7:G8,因此我可以将其用作参考。现在,在下一个区域之前跳过的列数可能会有所不同,以及在下一个区域之前跳过的行数可能会有所不同。所以我需要考虑这一点。

我有以下VBA代码:

Sub test()
'
' test Makro
'

'

Dim i As Integer, j As Integer
k = 2 'areas downwards'
l = 3 'areas rightwards'

Dim area As String
Let area = "F7:G8" 'first area, always the same'

Dim Upper_letter As String
Let Upper_letter = "F"

Dim Upper_nr As String
Let Upper_nr = "7"

Dim Lower_letter As String
Let Lower_letter = "G"

Dim Lower_nr As String
Let Lower_nr = "8"

For i = 1 To k

    For j = 1 To l

        area = area & "," & Upper_letter & Upper_nr ":" & Lower_letter & Lower_number
    'How do I add 3 letters to both Upper_letter and Lower_letter after each iteration of j?'

    Next j

   upper_nr = upper_nr + 3 'after each iteration of i, add 3'
   lower_nr = lower_nr + 3 'after each iteration of i, add 3'

Next i

End Sub

所以我没有看到如何在最里面的循环中添加字母。

1 个答案:

答案 0 :(得分:1)

请试试这个:

Sub ErosRam()
    Dim i&, j&, area$, k As Range, r As Range

    Const COL_PERIOD = 3
    Const ROW_PERIOD = 3
    Const REPS_HORIZONTAL = 3
    Const REPS_VERTICAL = 2

    Set r = [f7:g8]
    Set k = r

    For i = 0 To REPS_VERTICAL - 1
        For j = 0 To REPS_HORIZONTAL - 1
            Set k = Union(k, r.Offset(i * ROW_PERIOD, j * COL_PERIOD))
        Next
    Next

    area = k.Address(0, 0)
    MsgBox area   
End Sub

您可以修改顶部的Const行来更改期间和重复次数。