Marking an area with a double 'For' loop

佐手、 提交于 2020-01-07 03:52:13

问题


I am trying to do the following: I want to store different areas (marked in yellow) in a string. The first yellow area is F7:G8, second is I7:J8 and so on, such that the string becomes: "F7:G8,I7:J8,L7:M8,F10:G11,I10:J11, L10:M11".

So in this example I have three areas to the right, and two down. The number of areas to the right and downwards may vary, therefore I want to make a code where I only have to specify how many areas to the right and downwards. Note that the first area always is F7:G8, so this I can use as a reference. Now, how many columns one skips before next area might vary, and also how many rows one skips before next area might vary. So this I need to take into account.

I have the following VBA code:

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

So I fail to see how I can add letters, in the innermost loop.


回答1:


Please try this:

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

You can edit the Const lines at the top to change the period and the number of repetitions.



来源:https://stackoverflow.com/questions/33263658/marking-an-area-with-a-double-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!