从Access到Excel文件写入数据

时间:2008-11-11 12:12:48

标签: excel vba excel-vba ms-access

我正在尝试使用以下代码将数据写入excel文件

     Dim objexcel As Excel.Application
                     Dim wbexcel As Excel.Workbook
                     Dim wbExists As Boolean
                     Set objexcel = CreateObject("excel.Application")
                     objexcel.Visible = True
                     On Error GoTo Openwb
                     wbExists = False
                     Set wbexcel = objexcel.Documents.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
                     wbExists = True
Openwb:

                     On Error GoTo 0
                     If Not wbExists Then
                     Set wbexcel = objexcel.Workbook.Add
                     End If

但我得到了

  

运行时错误对象不支持属性或方法

Set wbexcel = objexcel.Workbook.Add

我引用了Excel对象库。

2 个答案:

答案 0 :(得分:7)

您需要更改此行:

 Set wbexcel = objexcel.WorkBooks.Open( _
    "C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")     

注意工作簿,而不是文档

对于此行设置wbexcel = objexcel.Workbook.Add,wbexcel被定义为工作簿,但该行是一个动作,因此:

objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook

编辑: 另外,DoCmd.Transferspreadsheet可能是将一组数据(查询,表)从Access传输到Excel的最简单方法。

答案 1 :(得分:0)

我有这个代码可以正常使用

Dim objexcel As Excel.Application
                     Dim wbexcel As Excel.Workbook
                     Dim wbExists As Boolean
                     Dim objSht As Excel.Worksheet
                     Dim objRange As Excel.Range


                     Set objexcel = CreateObject("excel.Application")
                     objexcel.Visible = True
                     On Error GoTo Openwb
                     wbExists = False
                     Set wbexcel = objexcel.Workbooks.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\reports\ERROR REPORT2.xls")
                     Set objSht = wbexcel.Worksheets("Sheet1")
                     objSht.Activate
                     wbExists = True
Openwb:

                     On Error GoTo 0
                     If Not wbExists Then
                     objexcel.Workbooks.Add
                     Set wbexcel = objexcel.ActiveWorkbook
                     Set objSht = wbexcel.Worksheets("Sheet1")

                     End If

但是我想再添加一个检查,如果文件存在,那么我想看看它是否填充了值,如果是,那么我希望从末尾填充下一组值。截至目前,它正在覆盖现有值