如何使用两个动态变量创建循环?

时间:2019-10-29 13:25:20

标签: excel vba

我有多个需要特殊内部颜色和值的单元格(“位置”)。 这些单元格中的每个单元格都与另一个工作表中其自己的相应单元格关联。

目前我大约有35个职位,但将来可能会有150个职位,因此手动添加这些职位将很繁琐!这是我目前的代码:

Dim FirstSheet As Worksheet
Dim Secondsheet As Worksheet
Dim position1 As Range
Dim position2 As Range
Dim position3 As Range
Dim lnCol As Long

Set FirstSheet As ThisWorkbook.Worksheets("FirstSheet")
Set SecondSheet As ThisWorkbook.Worksheets("SecondSheet")
Set position1 = Firstsheet.Range("G11")
Set position2 = Firstsheet.Range("F11")
Set Position3 = Firstsheet.Range("E11")
lnCol = 'this is a column number which is found earlier in the sub.

position1.Interior.Color = SecondSheet.Cells(8, lnCol).Interior.Color
position2.Interior.Color = SecondSheet.Cells(9, lnCol).Interior.Color
position3.Interior.Color = SecondSheet.Cells(10, lnCol).Interior.Color
position1.Offset(2, 0).Value = SecondSheet.Cells(8, lnCol).Value
position2.Offset(2, 0).Value = SecondSheet.Cells(9, lnCol).Value
position3.Offset(2, 0).Value = SecondSheet.Cells(10, lnCol).Value

理想情况下,我想要一个循环,该循环将使用同时更改的两个数组,但是我不知道如何使其工作!这是我希望看到的示例:

For Each PositionVar In Array(position1, position2, position3)
    PositionVar.Interior.Color = dynamicvariable.Interior.Color
    PositionVar.Offset(2,0).Value = dynamicvariable.Value
Next PositionVar

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

您为什么不使用堆叠在一起的两个循环来解决此问题?例如:

for each rng in Array(Range1, Range2, Range3)
    for each position in rng
       'Do whatever you like with this Range
    next position
next rng

答案 1 :(得分:0)

您可以使用:

Option Explicit

Sub test()

    Dim i As Long, y As Long, LastColumn As Long, Counter As Long, lnCol As Long
    Dim ws1 As Worksheet, ws2 As Worksheet

    Counter = 8
    lnCol = 3 'Change value

    With ThisWorkbook
        'Set the sheet with positions
        Set ws1 = .Worksheets("Sheet1")
        'Set the second sheet
        Set ws2 = .Worksheets("Sheet2")
    End With

    With ws1
        'Find the LastColumn of row 11
        LastColumn = .Cells(11, .Columns.Count).End(xlToLeft).Column

        'Loop from the last column until column 5th
        For i = LastColumn To 5 Step -1

            With .Cells(11, i)
                .Interior.Color = ws2.Cells(Counter, lnCol).Interior.Color
                .Offset(2, 0).Value = ws2.Cells(Counter, lnCol).Value
            End With

            Counter = Counter + 1

        Next i

    End With

End Sub

注意 使用“最后一列”的局限性在于,如果第11行中没有值,则应使用变量而不是最后一列来指代您想要的列的总值

答案 2 :(得分:0)

通过使用数组和控制变量设法找到答案。您只需要确保相应变量的顺序相同即可。希望这对其他人有帮助。

Dim PositionArray As Variant
Dim SecondSheetArray As Variant
Dim i As Variant 

PositionArray = Array(position1, position2, position3) 
SecondSheetArray = Array(SecondSheet1, SecondSheet2, SecondSheet3) 

For i = 0 To UBound(PositionArray)
    PositionArray(i).Interior.Color = OverviewArray(i).Interior.Color
    PositionArray(i).Offset(2, 0).Value = OverviewArray(i).Value
Next i