我在ms访问中有以下公共功能:
'source: https://support.microsoft.com/en-us/kb/246335
Public Function COV(rs1 As DAO.Recordset, rs2 As DAO.Recordset, Returns As String) As Double
Dim xlapp As Object, xlWb As Object, xlWs As Object, ar1 As Object, ar2 As Object
' Create an instance of Excel and add a workbook
Set xlapp = CreateObject("Excel.Application")
Set xlWb = xlapp.Workbooks.Add
Set xlWs = xlWb.Worksheets("Sheet1")
'Undisplay Excel and give user control of Excel's lifetime
xlapp.Visible = True
xlapp.UserControl = True
' ' Copy the recordset to the worksheet, starting in cells A1 and A2
xlWs.Range("A1").CopyFromRecordset rs1
xlWs.Range("F1").CopyFromRecordset rs2
Set ar1 = xlWs.Range("D:D")
Set ar2 = xlWs.Range("I:I")
'Set ar1 = xlWs.Range("D1:D" & CStr(rs1.RecordCount))
'Set ar2 = xlWs.Range("I1:I" & CStr(rs2.RecordCount))
COV = xl.WorksheetFunction.COVARIANCE_P(ar1, ar2)
Set ar1 = Nothing
Set ar2 = Nothing
Set xlWs = Nothing
Set xlWb = Nothing
Set xlapp = Nothing
End Function
我有一个运行时错误'424':协方差应用程序行所需的对象:
COV = xl.WorksheetFunction.COVARIANCE_P(ar1, ar2)
协方差函数无法识别对象ar1和ar2。我把对象xlapp看得见,我在Excel中得到了这个表: 因此,当我在工作表中直接运行协方差函数时,它可以工作,但在ms访问vba,没有。