2011-12-13 53 views
2

我是訪問和VBA的新手。我有一個函數用來計算中位數。當前函數充當域函數,並使用所有數據計算中位數,而不是構成查詢/報告其餘部分的數據集。我想知道如何修改此代碼或更好的方法來查找用於創建報告的數據集的中位數。訪問中的數據集的最佳VBA方法

Option Compare Database 
Option Explicit 



Function DMedian(tName As String, fldName As String) As Single 
    Dim MedianDB As DAO.Database 
    Dim ssMedian As DAO.Recordset 
    Dim RCount As Integer, i As Integer, x As Double, y As Double, _ 
     OffSet As Integer 
    Set MedianDB = CurrentDb() 
    Set ssMedian = MedianDB.OpenRecordset("SELECT [" & fldName & _ 
      "] FROM [" & tName & "] WHERE [" & fldName & _ 
      "] IS NOT NULL ORDER BY [" & fldName & "];") 
    'NOTE: To include nulls when calculating the median value, omit 
    'WHERE [" & fldName & "] IS NOT NULL from the example. 
    ssMedian.MoveLast 
    RCount% = ssMedian.RecordCount 
    x = RCount Mod 2 
    If x <> 0 Then 
    OffSet = ((RCount + 1)/2) - 2 
    For i% = 0 To OffSet 
     ssMedian.MovePrevious 
    Next i 
    DMedian = ssMedian(fldName) 
Else 
    OffSet = (RCount/2) - 2 
    For i = 0 To OffSet 
     ssMedian.MovePrevious 
    Next i 
    x = ssMedian(fldName) 
    ssMedian.MovePrevious 
    y = ssMedian(fldName) 
    DMedian = (x + y)/2 
    End If 
    If Not ssMedian Is Nothing Then 
    ssMedian.Close 
    Set ssMedian = Nothing 
    End If 
    Set MedianDB = Nothing 
End Function 

回答

0

如果你指的是計算對你已經創建了一個自定義報表中位數,那麼只需保存你的查詢,並以「TNAME」,而不是一個表名通過查詢名稱。

+0

有趣的答案,馬特。我從來沒有從這個角度來看待它。我試圖使用報告基於的查詢。 Dmedian(「qrySearch」,「SoldPrice」)報告本身基於相同的查詢。我得到這部分代碼的錯誤:Set ssMedian = MedianDB.OpenRecordset(「SELECT [」&fldName&_「] FROM [」&tName&「] WHERE [」&fldName&_「]不是NULL ORDER BY [「&fldName & "];」) – user1096276 2011-12-15 19:57:30

相關問題