excel - 引用 Excel 时,AutoCAD 中的 VBA 错误不一致

标签 excel vba autocad

我有一个程序可以查看 excel 文件中的 .dwg 文件列表,一次打开一个图纸,提取给定 block 引用的属性,然后将这些属性转储到原始 excel 文件中的新工作表中。

这段代码大约有一半时间运行得非常好,所有数据都被正确计算和格式化,但另一半时间我得到运行时错误 9、91 或 462。

我将错误放在括号中的行中。

我的代码中是什么导致了这些错误,如果这不是编程问题,那么为这些错误编写 ErrorHandler 的最佳方法是什么?

Set ExcelApp = GetObject(, "Excel.Application")
If ExcelApp Is Nothing Then
    Set ExcelApp = CreateObject("Excel.Application")
    If Not ExcelApp Then
        ExcelApp.Workbooks.Open (tempName)
    End If
End If

ExcelApp.DisplayAlerts = False
ExcelApp.Visible = False
Set wBook = ExcelApp.ActiveWorkbook
DoEvents

shtCount = wBook.Worksheets.Count ' ' (Error 91)
If shtCount <> 1 Then
    DoEvents
    wBook.Worksheets("Dump").Delete ' ' (Error 9, Despite that sheet existing)
    DoEvents
End If

Set wSheet = wBook.Worksheets.Add(After:=Worksheets("DrawSheets")) ' ' (Error 462)
DoEvents
wSheet.Name = "Dump"
DoEvents

最佳答案

在第一次审查时,这个代码块有几个问题:

Set ExcelApp = GetObject(, "Excel.Application")
If ExcelApp Is Nothing Then
    Set ExcelApp = CreateObject("Excel.Application")
    If Not ExcelApp Then
        ExcelApp.Workbooks.Open (tempName)
    End If
End If

该声明:
Set ExcelApp = GetObject(, "Excel.Application")

如果 Excel 未打开,将引发运行时错误;大概,你有On Error Resume Next出现在您的代码中以绕过此错误,或者您可能在测试中打开了 Excel。

如果 Excel 已经打开,您的代码将永远不会打开您的目标工作簿,因为代码不会到达语句:
ExcelApp.Workbooks.Open (tempName)

此外,if围绕上述表达式的语句没有意义:
If Not ExcelApp Then
    ExcelApp.Workbooks.Open (tempName)
End If

在这里,您是说:“如果 ExcelApp 评估为 False,则使用它打开工作簿”

关于excel - 引用 Excel 时,AutoCAD 中的 VBA 错误不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55618848/

相关文章:

excel - 具有不同系统设置的正确格式的当前 UTC 时间

vba - powerpoint vba 文本效果调整 handle

c# - 在 AutoCAD (C#) 中绘制带网格的盒子

java - 将 HTML 表格导出到 Excel - 使用 jQuery 或 Java

excel - 如何将组合文本日期格式化为等效日期?

vba - 有 protected 工作表时如何保持宏运行?

visual-c++ - 使用 LISP 加载和卸载 .arx 文件

c# - 在 AutoCAD 中获取实体的子实体顶点

每个工作表循环的 Excel VBA

vba - 减少资源计算搜索功能