多选在Access 2013中具有多列的列表框

时间:2014-10-22 16:17:11

标签: ms-access listbox access-vba multi-select

我有一个列表框设置为Simple的Multiselect属性。 使用表填充列表框。 列表框中有4列

1    3/23/2014    4/5/2014    2014
2    4/6/2014     4/19/2014   2014
3    4/20/2014    5/3/2014    2014

列是PayPeriod,StartDate,EndDate,FiscalYear

我希望能够做的是突出显示一大块日期并让第一个选定的StartDate和最后选择的EndDate填充两个隐藏文本框,以便我可以将它们用于我的查询/报告。

我尝试了几种不同的方法。每次发生的事情是它只使用我在其计算中选择的最后一项。

Dim ItemIndex As Variant
For Each ItemIndex In Me.lstPayPeriods.ItemsSelected
    If Me.lstPayPeriods.Selected(ItemIndex) And Me.lstPayPeriods.Selected(ItemIndex - 1) = False Then
    Date1.SetFocus
    Date1.Text = Me.lstPayPeriods.Column(2, Me.lstPayPeriods.ListIndex)
End If
Next

在这个例子中,我尝试让它遍历列表框的每个项目。我想检查一下当前行是否被选中以及它之前的行是不是。这样我就可以确定它是在所选项目组中选择的第一个项目。它总是只使用我选择的最后一项。

Dim CurrentRow As Integer
Dim FirstDate As Date

For CurrentRow = 0 To Me.lstPayPeriods.ListCount - 1
If Me.lstPayPeriods.Selected(CurrentRow) Then
    Date2.SetFocus
    Date2.Text = Me.lstPayPeriods.Column(3, Me.lstPayPeriods.ListIndex)
End If
Next CurrentRow

For CurrentRow = 0 To Me.lstPayPeriods.ListCount - 1
If Me.lstPayPeriods.Selected(CurrentRow) And Me.lstPayPeriods.Selected(CurrentRow - 1) = False Then
    Date1.SetFocus
    Date1.Text = Me.lstPayPeriods.Column(2, Me.lstPayPeriods.ListIndex)
End If
Next CurrentRow

我试着用这段代码做类似的事情。同样,它只使用我选择的最后一项。

我正在碰壁,弄清楚如何实现我的目标。

1 个答案:

答案 0 :(得分:0)

我认为问题在于你的方法。我个人并不热衷于确定最早开始和最新结束的方法,尽管问题可能只是您的列号:列表框中的第一列是第0列,最后一列是第4列)是第3列。因此,在上面的代码中,您设置的是Date2 =会计年度,而不是enddate。

然而,我建议采用不同的方法来确定(a)最早选择的StartDate,以及(b)最新选择的Enddate。你可以为每个操作设置一个循环,或者你可以将它们封装在一个函数中:

private function GetPayPeriodDate(baseValue as Date, findLater as boolean, colNo as long) as Date
    'baseValue is the default date to test against
    'findLater tells the function whether to look for < or > the baseValue
    'colNo tells the function which column of data to test

    Dim vv as variant
    For each vv in lstPayPeriods.ItemsSelected
        if lstPayPeriods.Selected(vv) then
            if findLater then
                if lstPayPeriods.Column(colNo, vv) > baseValue then
                    baseValue = lstPayPeriods.Column(colNo, vv)
                end if
            else
                if lstPayPeriods.Column(colNo, vv) < baseValue then
                    baseValue = lstPayPeriods.Column(colNo, vv)
                end if
            end if
        end if
    next vv
    GetPayPeriodDate = baseValue
end function

然后,您可以通过调用此函数来设置开始日期和结束日期文本框:

me.StartDate = GetPayPeriodDate(CDate("31/12/2099"), false, 1)
    'since startdate looks for the earliest date, the base date must be in the future
me.EndDate = GetPayPeriodDate(CDate("01/01/1900"), true, 2)
    'similarly, looking for the latest date, base date must be in the past