在循环VBA中输出重复事件

时间:2016-09-16 14:53:44

标签: excel vba excel-vba

我目前正在分析一个时间表,颜色编码事件连续发生,时间在列上扩展(单元格中只有颜色没有文字,是的,它是愚蠢的,但它不受我的控制)。我目前能够将一个事件发生的结果打印到另一个工作表中,但我无法确定如何在不同的单元格中打印重复事件的日期(它目前仅打印事件发生的最后一次)。我目前的代码是:

For i = 2 To 93
    If Cells(7, i).Interior.Color = "8421631" And Cells(7, i - 1).Interior.Color = "16777215" Then
        startDay = Cells(3, i).Value
        startMonth = Cells(1, i).Value
        name = Cells(7, i).Value
        Worksheets("Sheet1").Activate
        ActiveWorkbook.Worksheets("Sheet1").Cells(2, 1) = startDay + startMonth

    End If
    If Cells(7, i).Interior.Color = "8421631" And Cells(7, i + 1).Interior.Color = "16777215" Then
        endDay = Cells(3, i).Value
        endMonth = Cells(1, i).Value
        ActiveWorkbook.Worksheets("Sheet1").Cells(2, 2) = endDay + endMonth
    End If
Next i

我的所有变量都以字符串形式输入。我尝试了几种不同的方法但没有成功。我觉得我需要在我的IF语句中添加另一个循环,但我不确定如何做到最好。 总体而言,代码实现了它的目的(以前用于输出的消息框以确认它正在按预期运行)。这只是整个代码的一小部分,但是通过这个答案,我将能够将它应用于其他地方。

1 个答案:

答案 0 :(得分:0)

根据您的描述,您可以尝试使用此代码:

Option Explicit

Sub main()
    Dim i As Long

    For i = 2 To 93
        If Cells(7, i).Interior.Color = "8421631" Then
            If Cells(7, i - 1).Interior.Color = "16777215" Or Cells(7, i + 1).Interior.Color = "16777215" Then
                WriteDate Cells(3, i).Value, Cells(1, i).Value
            End If
        End If
    Next i
End Sub

Sub WriteDate(day As String, month As String)
    With ActiveWorkbook.Worksheets("Sheet1")
        .Cells(2, .Columns.Count).End(xlToLeft).Offset(, 1) = day & "/" & month
    End With
End Sub