在一个项目中使用了 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