如何获取导入Excel的Access数据集的中位数?

时间:2017-06-08 19:59:07

标签: excel vba excel-vba ms-access

Access没有原生中值函数,所以我正在使用这个UDF:

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

这会产生错误:

Run-time error '3085':

Undefined function 'fmedian' in expression.

我知道这里的问题是Excel无法读取使用UDF的Access查询。那么如何将此Access数据拉入Excel并仍具有中位数?

1 个答案:

答案 0 :(得分:0)

如果您将Access查询修改为“创建新表”,则所需的所有数据都将存储在此表中,然后您可以将Excel附加到此表。由于Excel只是通过预先计算的数字,你将没有问题。