Excel VBA formula, called from a cell, stops processing VBA, or encounters an App-Defined error, when a worksheet cell is written to
I have this formula in a cell:
=GetData("Channel_01","Chicago")
Which executes this code:
Public Function GetData(ChannelCode As String, Key As String) As String
Dim sql As String
Dim cmd As New ADODB.Command
Dim outputTo As Range
Set outputTo = Application.Caller
sql = "select * from ChannelData WHERE ChannelCode = ? AND Key1 = ?"
Set cmd = getCommand(sql, ChannelCode, Key)
Dim rs As ADODB.Recordset
Set rs = cmd.Execute
WritePivotRecordset ChannelCode, rs, outputTo.Offset(1, 0)
End Function
Public Sub WritePivotRecordset(ChannelCode As String, rs As ADODB.Recordset, destination As Range)
Dim i As Integer
'*** WHEN THIS LINE OF CODE IS REACHED AND EXECUTES, PROCESSING STOPS
Set destination.Value = ChannelCode
For i = 1 To rs.Fields.Count - 1 'skip first field
destination.Offset(0, i).Value = rs.Fields(i).Name
Next
destination.Offset(1, 0).CopyFromRecordset rs
End Sub
The problem occurs on this line:
'*** WHEN THIS LINE OF CODE IS REACHED AND EXECUTES, PROCESSING STOPS
Set destination.Value = ChannelCode
Is setting this invoking a spreadsheet recalc, which terminates the executing VBA thread or something like that? I thought so, so I tried this before writing any output:
Application.Calculation = xlCalculationManual
But now on that same line of code I get: Application-defined or obje开发者_C百科ct-defined error.
Is writing from a VBA function to the same worksheet from which the VBA function is called, just not allowed?
This is just the built-in behavior of Excel. Functions called from the worksheet (often called UDFs in Excel terminology - user-defined functions) can't do anything to the worksheet other than return a value.
In your code above, there appears to be another error, though.
Set destination.Value = ChannelCode
should fail because you're using the syntax for setting an object variable to an object reference. If you had an error handler in there it would catch the error. (Excel just terminates any UDF that lets an error go unhandled.) The line should be:
destination.Value = ChannelCode
However, your routine will still fail at that point because of the rule about UDFs not having side effects on cells. Note that even if you did have an error handler, it wouldn't catch that. VBA doesn't raise an error when a UDF tries to modify a cell; it just stops the UDF and returns a #VALUE! error.
In your case, it looks like you can rewrite your function to return an array containing the values you want, instead of trying to modify cells to the right and below of the calling cell. (Or you can call your function from some macro instead of a UDF.)
EDIT:
As far as returning the array, there is an ADO method - GetRows
- that will return one from a RecordSet:
code critique - am I creating a Rube Goldberg machine?
精彩评论