GoToRecord工作正常,但最简单的方法来返回该记录的值

时间:2019-02-26 06:32:56

标签: access-vba ms-access-2013 median goto

部分问题是打开记录集表,并且必须将焦点设置到子表单。我一直没有通过vba对表进行排序。目标是找到表的MEDIAN值,从而进行排序。

Private Sub cboUser_AfterUpdate()
Dim sourceReset As String
Dim dbMedian As DAO.Database
Dim rsMedian As DAO.Recordset

sourceReset = sbf.SourceObject  '<--Is Table.TEMPtable btw.
Me.sbf.SourceObject = ""
Forms!frm.Requery
Forms!frm.Refresh


'Create new TEMPtable
    DoCmd.SetWarnings False
    DoCmd.OpenQuery "qryTEMPtable"   '<--Is sorted here as desired
    DoCmd.SetWarnings True

Set dbMedian = CurrentDb()
Set rsMedian = dbMedian.OpenRecordset("TEMPtable") '<--Gets unsorted here

sbf.SourceObject = sourceReset
Me.OrderBy = "NetWrkDays ASC" '<--Re-sorting, but on subform, which.. is 
fine if I can return the column value later.
Forms!frm.Refresh

Me.[sbf].SetFocus

Records= DCount("[ColA]", "TEMPtable")

'Even number of records
If Records - 2 * Int(Records / 2) = 0 Then
    MEDrcd = Records / 2
    DoCmd.GoToRecord , , acGoTo, MEDrcd '<-Can see value in debug, how to 
assign it to a useful variable???
    ''''Me.CurrentRecord ("NetWrkDays")
    ''''Me.RecordSource ("NetWrkDays")
    Me.txtMED = rsMedian("NetWrkDays")
End If

'Odd number of records
If Records - 2 * Int(Records / 2) = 1 Then
    MEDrcd1 = (Records - 1) / 2
    MEDrcd2 = (Records + 1) / 2
    DoCmd.GoToRecord acDataForm, "TempTable", acGoTo, MEDrcd1
    MED1 = rsMedian("NetWrkDays")
    DoCmd.GoToRecord acDataForm, "TempTable", acGoTo, MEDrcd2
    MED2 = rsMedian("NetWrkDays")
    Me.txtMED = (MED1 + MED2) / 2
End If

我想如果您无法在那时返回值,那么尝试使用DoCmd.GoToRecord毫无意义。

  1. 移动到记录后返回值的最佳/正确方法是什么。

  2. 由于子表单和表相同,因此我只是将焦点设置为子表单,因为我说过在vba中对表进行排序时遇到问题。虽然那时我使用rsMedian毫无意义,因为rs表永远不会移动...但是我无法使用GoToRecord检索通过子窗体移动的值。

  3. 我在这里转圈,我希望不要混淆理解。谢谢。

1 个答案:

答案 0 :(得分:0)

在线找到了此方法。如果其他人也遇到类似的情况,那就很好了。

Private Sub cboUser_AfterUpdate()
Dim sourceReset As String, sqlMED As String, sTable As String, sField As String
Dim j As Integer, varVal As Single
Dim rs As DAO.Recordset

sourceReset = sbf.SourceObject
Me.sbf.SourceObject = ""
Forms!frmSTATS.Requery
Forms!frmSTATS.Refresh

   'Create new TEMPtable table
    DoCmd.SetWarnings False
    DoCmd.OpenQuery "qryTEMPtable"
    DoCmd.SetWarnings True

'Get MEDIAN Data/Value
sTable = "TEMPtable"
sField = "NetWrkDays"
sqlMED = "SELECT " & sField & " from " & sTable & " WHERE " & sField & ">0 Order by " & sField & ";"
Set rs = CurrentDb.OpenRecordset(sqlMED)
    rs.MoveLast
        j = rs.RecordCount
    rs.Move -Int(j / 2)

If j Mod 2 = 1 Then 'odd number of elements
   getMedian = rs(sField)
Else                'even number of elements
   varVal = rs(sField)
   rs.MoveNext
   varVal = varVal + rs(sField)
        getMedian = varVal / 2
End If
Me.txtAnswer = getMedian
rs.Close

sbf.SourceObject = sourceReset
Me.OrderBy = "NetWrkDays ASC"
Forms!frmSTATS.Refresh

结束子