2017-06-08 58 views
0

Access沒有本地值函數,所以我用這個UDF:如何獲取導入到Excel中的Access數據集的中位數?

Function fMedian(SQLOrTable, GroupFieldName, GroupFieldValue, MedianFieldName) 
    Dim rs As DAO.Recordset 

    Set db = CurrentDb 
    Set rs1 = db.OpenRecordset(SQLOrTable, dbOpenDynaset) 

    If Not (GroupFieldName = "" And GroupFieldValue = "") Then 
     If IsDate(GroupFieldValue) Then 
      GroupFieldValue = "#" & GroupFieldValue & "#" 
     ElseIf Not IsNumeric(GroupFieldValue) Then 
      GroupFieldValue = "'" & Replace(GroupFieldValue, "'", "''") & "'" 
     End If 

     rs1.Filter = GroupFieldName & "=" & GroupFieldValue 
    End If 

    rs1.Sort = MedianFieldName 

    Set rs = rs1.OpenRecordset() 
    rs.Move (rs.RecordCount/2) 

    If rs.RecordCount Mod 2 = 0 Then 
     varMedian1 = rs.Fields(MedianFieldName) 
     rs.MoveNext 
     fMedian = (varMedian1 + rs.Fields(MedianFieldName))/2 
    Else 
     fMedian = rs.Fields(MedianFieldName) 
    End If 

End Function 

,然後使用功能,如下面的例子查詢medianQuery

select fMedian("someTable","aGroupField",[aGroupField],"medianField") from someTable 

的問題是我想要導入的medianQuery結果到Excel報告(在Excel工作簿VBA)如下:

Sub importData(db As DAO.Database) 

Dim rs As DAO.Recordset 

Set rs = db.OpenRecordset(recordsetName, Options:=dbReadOnly) 

End Sub 

此機生產線ces錯誤:

Run-time error '3085': 

Undefined function 'fmedian' in expression. 

我知道這裏的問題是,Excel無法讀取使用UDF的Access查詢。那麼我怎樣才能把這個Access數據導入到Excel中,並且仍然有一箇中位數?

回答

0

如果您修改Access查詢以創建新表,您希望將所有數據存儲在此表中,則可以將Excel附加到此表中。由於Excel只是通過預先計算的數字,你將沒有問題。

相關問題