使用主窗体上子窗体的日期过滤值

Using a Date filtered value from a SubForm on the MainForm

我正在尝试获取已过滤的子窗体的最后一个条目,并将该单个值放在主窗体上。该条目也应该在 Date_0 和 Date_1 之间,虽然 Date_1 并非总是指定(在这种情况下,只需从 SubForm 中获取最后一个条目)。所以你得到了一个更图形化的想法(这是对真实表格的简化):

主窗体:

Date_0 Date_1 ValueToGet
2020/12/23 2021/02/27 Value from Subform

子表格:

Dates Values
2020/12/20 1200
2020/12/23 1189
2021/01/25 1173
2021/02/20 1165
2021/03/12 1333

在本例中,要从子表单收集​​的值是第四个条目(介于 Date_0 和 Date_1 之间,也是该日期范围内的最后一个条目)。然后,该值在窗体加载时存储在 MainForm 的 txtBox 中。我知道解决方案可能是在 txtBox 上设置一个 SQL 过滤器,但我不知道该怎么做。任何帮助将不胜感激。提前致谢!

你可以试试下面的子

Private Sub cmdGetResult_Click()
Dim strFilter As String
Dim rs As DAO.Recordset
    
    Me.Refresh
    
    strFilter = "[Dates] BETWEEN #" & Me.Date_0 & "# AND #" & Me.Date_1 & "#"

    Forms![Form1]![subformTest].Form.Filter = strFilter
    Forms![Form1]![subformTest].Form.FilterOn = True
    
    Set rs = Me.subformTest.Form.RecordsetClone
    
    rs.MoveLast
    Me.txtValueToGet = rs!values
    
    Forms![Form1]![subformTest].Form.FilterOn = False
    Set rs = Nothing
    
End Sub

OnLoad 事件可能为时过早,但像这样的事情应该有效:

Private Sub Form_Current()

    Dim Records As DAO.Recordset
    Dim Value   As Long
    Dim Found   As Boolean

    Set Records = Me!NameOfYourSubformControl.Form.RecordsetClone
    If Records.RecordCount > 0 Then
        Records.FindFirst "[Dates] >= #" & Format(Me!Date_0.Value, "yyyy\/mm\/dd") & "#"
        If Records.NoMatch Then
            ' No dates to look up.
        Else
            If IsNull(Me!Date_1.Value) Then
                Records.MoveLast
                Value = Records!Values.Value
                Found = True
            Else
                While Records.EOF = False And Found = False
                    If Records!Dates.Value >= Me!Date_1.Value Then
                        Value = Records!Values.Value
                        Found = True
                    End If
                    Records.MoveNext
                Wend
            End If
        End If
    End If
    Records.Close

    If Found = True Then
        Me!ValueToGet.Value = Value
    End If

End Sub