简体   繁体   English

Access 2010 Excel Export 1004错误

[英]Access 2010 Excel Export 1004 Error

I have some VBA in Access 2010 that runs a query and exports the results to a column in Excel. 我在Access 2010中有一些VBA,可以运行查询并将结果导出到Excel中的列。 The goal here is that when the user presses the required button an excel workbook is opened, if it doesn't exist then it is created. 目的是当用户按下所需的按钮时,将打开一个excel工作簿,如果该工作簿不存在,则会创建该工作簿。 When a new workbook is created the VBA preforms as expected. 创建新工作簿后,VBA将按预期执行。 The issue I'm having is when the workbook already exists. 我遇到的问题是工作簿已经存在。

So after I create an set my excel app object I attempt to open the workbook. 因此,在创建集合后,我的excel应用程序对象将尝试打开工作簿。 When it doesn't exist a 1004 error occurs and I have the following error handler: 当它不存在时,将发生1004错误,并且我具有以下错误处理程序:

    Select Case Err
    Case 1004   'Workbook doesn't exist, make it
    xl.Workbooks.Add
    Set wb = xl.ActiveWorkbook
    wb.SaveAs strWorkBook

    Resume Next

When the user opens an existing workbook they are prompted with an Overwrite Yes,No,Cancel options. 当用户打开现有工作簿时,系统会提示他们“覆盖是,否,取消”选项。 Any response other than yes generates a 1004 error (seems odd 2 different errors having same code #). 除“是”以外的任何响应都会产生1004错误(似乎有2个具有相同代码#的不同错误)。 I was just looking for a way around this, whether it be I write some VBA to automatically accept or I have something else that allows users to say no/cancel. 我只是在寻找解决此问题的方法,无论是编写一些自动接受的VBA还是让用户说不/取消的其他内容。 The easiest is preferred, I just don't want an error poping up on them. 最简单的方法是首选,我只是不希望在它们上弹出错误。

You don't need to rely on error handling to deal with whether or not the Excel file exists. 您不需要依靠错误处理来处理Excel文件是否存在。 Use Dir() to check whether it exists, and open or create accordingly. 使用Dir()检查它是否存在,并相应地打开或创建。

If Len(Dir(strFullPathToWorkbook)) > 0 Then
    ' open the workbook '
Else
    ' create the workbook '
End If

Use wb.SaveAs strWorkBook if this is a new workbook. 如果这是一个新工作簿,请使用wb.SaveAs strWorkBook

Use wb.Save if it's an existing workbook. 如果wb.Save是现有工作簿,请使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM