excel - 运行时错误 1004 方法添加对象表失败
问题描述
我正在尝试在工作簿中添加一张工作表,但出现了这个错误。有什么建议么?
运行时错误 1004 方法添加对象表失败
Do While MyFile <> ""
Workbooks.Open (MyFile)
Set ws = ActiveWorkbook.Sheets.Add(Before:=ActiveWorkbook.Sheets(1))
ws.Name = "Global OHS RA Form"
解决方案
避免使用ActiveWorkbook
. 将打开的工作簿设置为变量并直接使用它。
我还建议检查文件是否正确打开以及工作簿是否受到保护。
Do While MyFile <> vbNullString
Dim OpenedWb As Workbook
Set OpenedWb = Nothing ' initialize because looping
Set OpenedWb = Workbooks.Open(MyFile)
If Not OpenedWb Is Nothing Then ' check if file was opened properly
If OpenedWb.ProtectStructure Then ' check if workbook is protected
MsgBox "Workbook is protected, cannot add worksheets."
Else
Dim ws As Worksheet
Set ws = OpenedWb.Worksheets.Add(Before:=OpenedWb.Sheets(1))
ws.Name = "Global OHS RA Form"
' … your other code here
End If
Else
MsgBox "File could not be opened properly."
End If
Loop
推荐阅读
- sql - 如何将 XML 列从另一个表复制到一个表?
- javascript - 从排序数组的输出中删除逗号之前的所有内容
- vue.js - 使用 Vue 在某些路由/页面上执行事件的正确方法
- c# - 从 DbContext 加载实体时,Entity Framework Core 抛出 System.Data.SqlTypes.SqlNullValueException
- javascript - 即使设置了keepAliveTimeout,响应连接标头也具有值'close'
- javascript - 如何检测组件将使用反应挂钩更新?
- cumulocity - Cumulocity HTML 小部件
- javascript - 用声明词在打字稿中声明类
- c# - 查找大小调整操作中是否按下 Esc 键(MouseLeftButtonDown+MouseMove)
- storybook - 无法加载预设:1 级的“@storybook/addon-info”