Excel VBA,执行后选择语句更改

时间:2012-05-12 13:54:47

标签: sql oracle vba excel-vba excel

所以我遇到一个问题,我尝试设置为SQL查询的任何长字符串在尝试从记录集复制到Excel时会返回错误

例如,如果我使用像这样的查询

select 
cdf.DAY_STAMP Day, b.ACCOUNT_NUMBER Acct#, cdf.CM_DESC MAC, 
b.STREET_NUMBER St#, b.STREET_NAME StName, b.CITY City,
b.TRANSPORT_ELEMENT_2 census,
i.ifalias node,
cdf.SUM_BYTES_UP, cdf.SUM_BYTES_DOWN, cdf.SUM_RESET_COUNT, cdf.AVG_TXPOWER_UP,
cdf.MAX_TXPOWER_UP, cdf.MIN_TXPOWER_UP, cdf.AVG_RXPOWER_DOWN, cdf.MAX_RXPOWER_DOWN,
cdf.MIN_RXPOWER_DOWN, cdf.AVG_RXPOWER_UP, cdf.MAX_RXPOWER_UP, cdf.MIN_RXPOWER_UP,
cdf.AVG_PATH_LOSS_UP, cdf.AVG_CER_DOWN, cdf.MAX_CER_DOWN, cdf.MIN_CER_DOWN,
cdf.AVG_CCER_DOWN, cdf.MAX_CCER_DOWN, cdf.MIN_CCER_DOWN, cdf.AVG_SNR_DOWN,
cdf.MAX_SNR_DOWN, cdf.MIN_SNR_DOWN, cdf.US_CER_MAX, cdf.US_CCER_MAX, cdf.US_SNR_MIN,
cdf.STATUS_VALUE_MIN, cdf.TIMING_OFFSET_LAST, cdf.ROWCOUNT, cdf.T3_TIMEOUTS,
cdf.T4_TIMEOUTS, cdf.SYSUPTIME
from cm_day_facts cdf
inner join int_attributes i 
on i.ifalias like '72F007%' and i.topologyid = cdf.up_id
inner join billing_data b
on b.equipment_mac = cdf.cm_desc
where cdf.DAY_stamp >= '12-MAY-12 00:00'

我收到错误:关闭对象时不允许操作

但是,如果我使用如下查询:选择*来自" DWRVWR"。" CSOC_M_WIPMASTER"

我得到了一个没有问题的有效回复。

完整代码:

Sub CableData_SQLconn()

'Connect to Oracle server begin
Set sqlCon = New ADODB.Connection
Set sqlCommand = New ADODB.Command
Set sqlRecordSet = New ADODB.Recordset
Dim Conn As String
Dim sqlQuery As String
Dim sqlQuery2 As String
Dim sqlQuery3 As String

'grab node from user input box
node = InputBox("Node")

'Connection string
Conn = "Provider=MSDASQL; Driver={Microsoft ODBC for Oracle}; " & _
    "CONNECTSTRING=(DESCRIPTION=" & "(ADDRESS=(PROTOCOL=TCP)" & _ 
    "(HOST=myhost)(PORT=myport))" & "(CONNECT_DATA=(SID=mysid))); uid=user; pwd=pass;"

'Build SQL Query
sqlQuery = "A REALLY LONG STRING"
sqlQuery2 = sqlQuery & "A REALLY LONG STRING"
sqlQuery3 = sqlQuery2 & "A REALLY LONG STRING"

'This output is confirmed to have the full query - **VERIFIED OUTPUT IS CORRECT**
Range("A1").Select
ActiveCell.FormulaR1C1 = sqlQuery3

'---------------------------------------------------------------
' Set file details for SQL query
fileDir = "C:\temp\"
filePath = "C:\temp\" & node & "_SRO_TCs.sql"

'check if directory exists, if not create it
If Dir(fileDir, cbDirectory) = "" Then
MkDir fileDir
End If

' open the file output
Open filePath For Output As #1

'Write full SQL query to file - VERIFIED
outputText = sqlQuery3
Print #1, outputText
'-----------------------------------------------------------    


'open connection
sqlCon.ConnectionString = Conn
  'Cn.CursorLocation = adUseClient
sqlCon.Open

'set and execute sql command
Set sqlCommand.ActiveConnection = sqlCon
sqlCommand.CommandText = sqlQuery3
sqlCommand.CommandType = adCmdText
sqlCommand.Execute sqlQuery3

'open recordset
Set sqlRecordSet.ActiveConnection = sqlCon
sqlRecordSet.Open sqlCommand

'copy data to excel
'ActiveSheet.Range("A1").CopyFromRecordset (sqlRecordSet)
If Not sqlRecordSet.EOF Then    '<<<<<<<<<<<<<<<<<<<<<<<<<<< ERROR: Operation is not allowed when the object is closed
    ActiveSheet.Range("A1").CopyFromRecordset sqlRecordSet
Else: MsgBox "No records returned!"
End If

'close connections
sqlRecordSet.Close
sqlCon.Close

'Close file
Close #1

End Sub

1 个答案:

答案 0 :(得分:0)

使用您想要的任何参数将查询转换为存储过程,然后从Excel调用存储过程并将结果粘贴到工作簿中。在下面列出的示例中,我正在连接到SQL Server,但如果要连接到Oracle,它将工作相同。

以下是您可以修改以使用您的应用程序的一些代码:

    Public Sub RunStoredProcedureFromExcel()
    Dim rsData As ADODB.Recordset

    Dim ProductID, CategoryID, StoreNumber As Integer
    ProductID = Sheets("Variables").Range("nrProductID").Value
    CategoryID = Sheets("Variables").Range("nrCategoryID").Value
    StoreNumber = Sheets("Variables").Range("nrSelectedStore").Value

    ' Clear the destination worksheet
    Sheet39.UsedRange.Clear

    ' Set the ADODB Connection
    ConnectToSQLServer

    ' Create the Recordset object.
    Set rsData = New ADODB.Recordset

    ' Open the pooled connection
    mcnSQLServer.Open
    mcnSQLServer.espGetLookupData ProductID, CategoryID, StoreNumber, rsData

    If Not rsData.EOF Then

        ' Paste the results into workbook
        Sheet39.Range("a1").CopyFromRecordset rsData

    Else
        MsgBox "No data located.", vbCritical, "Error!"
    End If

    ' Close the pooled connection
    mcnSQLServer.Close

    End Sub

Professional Excel Development一书中有一个很好的章节,这是上面代码的起点。