如何根据用户表单 VBA 中的选定日期过滤列表框?

How do I filter a listbox based on selected date in Userform VBA?

我第一次在 VBA 中处理用户表单。我有一个日历用户表单,从中我 select 一个显示在文本框上的日期。默认情况下,文本框显示当前日期。在底部我有一个列表框。我想根据用户当前 date/date select 过滤列表框中的数据。

我正在这样做,但它确实会在列表框中产生任何结果。我需要将日期转换为其他类型吗?

Sub Attendance_Display_Listbox()
    Dim dsh As Worksheet
    Set dsh = ThisWorkbook.Sheets("Attendance")
     
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("AttendanceDisplay")
    
     '''Filter data datewise
    dsh.UsedRange.AutoFilter 5, "=" & Me.txt_Date.Value
    
    sh.Cells.ClearContents
    dsh.UsedRange.Copy
    sh.Range("A1").PasteSpecial xlPasteValues
    sh.Range("A1").PasteSpecial xlPasteFormats
    dsh.AutoFilterMode = False
    
    Dim last_row As Long
    last_row = Application.WorksheetFunction.CountA(sh.Range("A:A"))
    If last_row = 1 Then last_row = 2
    
    With Me.ListBox1
        .ColumnHeads = True
        .ColumnCount = 8
        .ColumnWidths = "0,50,200,150,70,50,100,70" '0 for not displaying the Serial no
        .RowSource = sh.Name & "!A2:H" & last_row
    End With
End Sub

换个日期 select 然后 -

Private Sub txt_Date_Change()
Call Attendance_Display_Listbox
End Sub
Dim dsh As Worksheet
    Set dsh = ThisWorkbook.Sheets("Attendance")
     
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("AttendanceDisplay")
    
    dsh.AutoFilterMode = False
    
    dsh.Range("E:E").NumberFormat = "D-MMM-YYYY"
    
    '''filter
    dsh.UsedRange.AutoFilter 5, "=" & Me.txt_Date.Value
    
    sh.UsedRange.Clear
    dsh.UsedRange.Copy
    sh.Range("A1").PasteSpecial xlPasteValuesAndNumberFormats

    dsh.AutoFilterMode = False
    
    Dim last_row As Long
    last_row = Application.WorksheetFunction.CountA(sh.Range("A:A"))
    If last_row = 1 Then last_row = 2
    
    With Me.ListBox1
        .ColumnHeads = True
        .ColumnCount = 8
        .ColumnWidths = "0,50,200,150,70,50,100,70" '0 for not displaying the Serial no
        .RowSource = sh.Name & "!A2:H" & last_row
    End With
 
End Sub

这有效!