我有一个简单的Excel VBA查询,它返回两个字段。如果我将它作为[Public Sub]运行它可以正常工作。如果它作为[公共功能]运行它失败。为什么会这样?两者之间有什么区别?
以下代码打开连接并查询数据。消息框:
1 - 显示75条记录
2 - 显示“准备写出记录”
3a - 如果作为函数运行,则第三个Messagebox永远不会触发。
3b - 如果作为SUB运行,则RecordSet内容将写入单元格A5:B81(来自上一行代码),并且消息框显示75条记录
有什么想法?我是VBA / Excel自动化的新手,但在其他地方有很多经验。
谢谢!
Public Function GetAccountList(cMainStart As String, cMainEnd As String)
' Check to see if data connection is open...if not, connect
' declares CON and RS. Opens Connection
OpenGLJSJ
Dim cSQL As String
Set rs = New ADODB.Recordset
Set rs.ActiveConnection = con
rs.CursorLocation = adUseClient
cSQL = "SELECT distinct Main, Sub From tblGLAccountsPeriodBalance where Main>='" & cMainStart & "' and Main<='" & cMainEnd & "'"
rs.Open cSQL, con, adOpenForwardOnly, adLockReadOnly, adCmdTxt
MsgBox rs.RecordCount
MsgBox "getting ready to write out records"
Worksheets("test").Range("a5").CopyFromRecordset rs
MsgBox rs.RecordCount
End Function