VBA Userform Code作为不同过滤条件的一部分在日期之间进行过滤

时间:2017-03-13 05:18:28

标签: excel vba date

我有一个userform,用于过滤数据集中的条件,并将信息填充到报告电子表格中。除了两个日期过滤器之外,所有过滤器都可以使用。

这是我到目前为止的代码;

Private Sub btnrun_Click()
Dim sdsheet As Worksheet, grsheet As Worksheet
   Dim sdlr As Long, grlr As Long, y As Long, x As Long

Set sdsheet = ThisWorkbook.Sheets("Governance Reporting Data")
   Set grsheet = ThisWorkbook.Sheets("Governance Report")
   Dim match As Boolean
   match = False

sdlr = Application.Max(sdsheet.Cells(Rows.Count, 4).End(xlUp).Row, 2)

grlr = Application.Max(grsheet.Cells(Rows.Count, 1).End(xlUp).Row, 2)
y = 2

Me.Hide

'make sure date format
If Not IsDate(Me.tbentrydatefirst) And Me.tbentrydatefirst <> "" Then
MsgBox "Please enter correct date format"
Me.tbentrydatefirst = ""
Exit Sub
End If

If Not IsDate(Me.tbentrydatelast) And Me.tbentrydatelast <> "" Then
MsgBox "Please enter correct date format"
Me.tbentrydatelast = ""
Exit Sub
End If


'populate data based on variables
For x = 5 To sdlr

    If Me.cmbmonth = "All" Or sdsheet.Cells(x, 2) = Me.cmbmonth Then
    If CDate(Me.tbentrydatefirst.Value) >= DateValue(sdsheet.Cells(x,     3).Value) And CDate(Me.tbentrydatelast.Value) <= DateValue(sdsheet.Cells(x, 3).Value) Then
    If Me.cmbprovider = "All" Or sdsheet.Cells(x, 4) = Me.cmbprovider Then
    If Me.cmbcontractofficer = "All" Or sdsheet.Cells(x, 5) = Me.cmbcontractofficer Then
    If Me.cmbissue = "All" Or sdsheet.Cells(x, 7) = Me.cmbissue Then
    If Me.cmbstatus = "All" Or sdsheet.Cells(x, 12) = Me.cmbstatus Then

        grsheet.Cells(y, 1).Resize(1, 10).Value = sdsheet.Cells(x, 3).Resize(1, 10).Value
        y = y + 1
        match = True

    End If
    End If
    End If
    End If
    End If
    End If




Next


grsheet.Visible = True
grsheet.Activate

If Me.cbprintpreview = True Then grsheet.PrintPreview

If MsgBox("Would you like to close this report?", vbYesNo, "Close Report?") = vbYes Then
    grsheet.Visible = False
    grsheet.Range("A2:J150").ClearContents
End If

Unload Me

End Sub

任何建议???

1 个答案:

答案 0 :(得分:1)

您的情况不正确:

If CDate(Me.tbentrydatefirst.Value) >= DateValue(sdsheet.Cells(x, 3).Value) And CDate(Me.tbentrydatelast.Value) <= DateValue(sdsheet.Cells(x, 3).Value) Then

这应该是:

If CDate(Me.tbentrydatefirst.Value) <= DateValue(sdsheet.Cells(x, 3).Value) And CDate(Me.tbentrydatelast.Value) >= DateValue(sdsheet.Cells(x, 3).Value) Then