0

我的代码是查找用户在 Excel 表中输入的开始和结束日期,以便用户可以找到输入日期期间的产品转换次数。如果用户输入了行中存在的开始日期和结束日期,它可以正常工作。问题是当用户输入行中不存在的开始和结束日期时,它会给出产品转换数=0。例如,我的数据包含从 2013 年 1 月 2 日到 2013 年 1 月 28 日的日期,其中包含 10 次产品转换。但是当用户输入开始日期 = 2013 年 1 月 1 日,结束日期 = 2013 年 1 月 29 日(行中不存在的日期)时,转换次数为 0。我想要做的是如果日期不是行中存在,程序会自动跳转到最近的日期。这是我的代码:

Dim rowFound As Variant
Dim startDate As String, endDate As String, startDateRow As Long
Dim endDateRow As Long, product As String, convNo As Long

Set ws2 = ActiveWorkbook.Sheets("Products Conversion")
Set wsMain = ActiveWorkbook.Sheets("Main Menu")

ws2.Activate
lastrow2 = ws2.Range(Range("A1"), Range("A65535").End(xlUp)).count ' find lastrow
wsMain.Activate

startDate = Me.txtStartDate.Value

endDate = Me.txtEndDate.Value

On Error Resume Next
If txtStartDate <> "" Or txtEndDate <> "" Then

For i = 3 To lastrow2

    If CDate(startDate) = ws2.Cells(i, 1).Value Then
        startDateRow = i   ' row where start date is
        Exit For
    End If

Next


For j = lastrow2 To 3 Step -1

    If CDate(endDate) = ws2.Cells(j, 1).Value Then
        endDateRow = j      ' row where end date is
        Exit For
    End If

Next

For k = startDateRow To endDateRow - 1

    product = ws2.Cells(k, 6).Value

    If product <> ws2.Cells(k + 1, 6).Value Then
        convNo = convNo + 1 'number of conversion
    End If

Next

Else
MsgBox "Please enter both date!", vbOKOnly + vbCritical
End If

Me.txtConvNo.Value = convNo
4

1 回答 1

1

好吧,我终于可以弄清楚了。只需添加一些循环

Dim rowFound As Variant
Dim startDate As String, endDate As String, startDateRow As Long
Dim endDateRow As Long, product As String, convNo As Long

Set ws2 = ActiveWorkbook.Sheets("Products Conversion")
Set wsMain = ActiveWorkbook.Sheets("Main Menu")

ws2.Activate
lastrow2 = ws2.Range(Range("A1"), Range("A65535").End(xlUp)).count ' find lastrow
wsMain.Activate

startDate = Me.txtStartDate.Value

endDate = Me.txtEndDate.Value

On Error Resume Next
If txtStartDate <> "" Or txtEndDate <> "" Then

resume1:
For i = 3 To lastrow2

    If CDate(startDate) = ws2.Cells(i, 1).Value Then
        startDateRow = i ' row where start date is
        Exit For
    End If

Next

If startDateRow = 0 Then 'date entered not found in the row
    startDate = CDate(startDate) + 1
    GoTo resume1
End If

resume2:
For j = lastrow2 To 3 Step -1

    If CDate(endDate) = ws2.Cells(j, 1).Value Then
        endDateRow = j ' row where end date is
        Exit For
    End If


Next 

If endDateRow = 0 Then 'date entered not found in the row
    endDate = CDate(endDate) - 1
    GoTo resume2
End If

Next

For k = startDateRow To endDateRow - 1

product = ws2.Cells(k, 6).Value

If product <> ws2.Cells(k + 1, 6).Value Then
    convNo = convNo + 1 'number of conversion
End If

Next

Else
MsgBox "Please enter both date!", vbOKOnly + vbCritical
End If

Me.txtConvNo.Value = convNo
vba excel-vba 
于 2013-05-09T09:31:06.160 回答