使用QueryTables生成Excel數據時發生錯誤

在一個項目中使用了 QueryTables 方法生成Excel,結果在客戶端安裝Excel2003時正常,安裝Excel2007時發生錯誤,無法生成Excel。

查了下MSDN 得知,與引用的MS 組件有關係。

詳情說明:http://support.microsoft.com/kb/263498/zh-cn

重現行爲的步驟

下面的步驟演示了自動化 Excel 從 Visual Basic 客戶端的同時,您就可能會收到此錯誤。但是,您應注意此問題可能出現的任何客戶端的自動化 Excel 並不是特定於 Visual Basic 自動化客戶端。


  1. 在 Visual Basic 中創建一個新的 標準 EXE 項目。默認情況下創建 Form1
  2. Form1 添加一個 命令按鈕 控件。
  3. 項目 菜單上單擊 引用
  4. 單擊對象庫,您的 Excel 版本。例如對於單擊下列選項之一:
    • 選擇 Microsoft Office Excel 2007 年的 Microsoft Excel 12.0 對象庫
    • 選擇 Microsoft Office Excel 2003 年的 Microsoft Excel 11.0 對象庫
    • 對於 Microsoft Excel 2002,選擇 Microsoft Excel 10.0 對象庫
    • 對於 Microsoft Excel 2000 中,選擇 Microsoft Excel 9.0 對象庫
  5. 選擇下列選項之一:
    • Microsoft ActiveX 數據對象 2.6
    • Microsoft ActiveX 數據對象 2.5
  6. 單擊 確定 以關閉 引用 對話框。
  7. 將下面的代碼添加到 命令按鈕Click 事件:
    
        Dim xlApp As Excel.Application
        Dim xlBook As Excel.Workbook
    
        Dim xlSheet As Excel.Worksheet
        Dim cn As ADODB.Connection
        Dim rs As ADODB.Recordset
        Dim cmd As ADODB.Command
        Dim oQueryTable As Excel.QueryTable
        
        'Start a new workbook in Excel
        Set xlApp = CreateObject("Excel.Application")
        xlApp.Visible = True
        xlApp.UserControl = True
        Set xlBook = xlApp.Workbooks.Add
        Set xlSheet = xlBook.Worksheets(1)
        
        'Connect to local SQL Server. You will need to replace <username> and <strong password>
        'with the User ID and password of an account who has appropriate permissions.
        Set cn = New ADODB.Connection
        cn.Open "Provider=SQLOLEDB.1;Data Source=YourServer;" & _
                "Password=<strong password>;User ID=<username>;Initial Catalog=Northwind"
        
        'Generate the recordset
        Set rs = New ADODB.Recordset
        rs.Open "Select * from Products", cn
        
        'Create the query table on the worksheet
        Set oQueryTable = xlSheet.QueryTables.Add(rs, xlSheet.Cells(1, 1))
        oQueryTable.Refresh
        
        'Close the recordset and the connection
        rs.Close
        cn.Close
        Set rs = Nothing
        Set cn = Nothing
    					
    : 此代碼示例從生成的記錄集上 SQL Server 羅斯文數據庫。在連接字符串"YourServer"改爲您 SQL Server 的名稱。
     
  8. 按 F5 鍵運行該的應用程序,然後單擊 命令按鈕

    結果: 嘗試添加 查詢表 的代碼的行生成運行時錯誤消息"5。

若要更正此錯誤,修改代碼,以使記錄集使用客戶端遊標。在代碼示例中更改以下


'Generate the recordset
Set rs = New ADODB.Recordset
rs.Open "Select * from Products", cn
				

到:


'Generate the recordset
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open "Select * from Products", cn
				
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章