简体   繁体   English

使用Word VBA创建Excel工作表的副本

[英]Create Copy Of Excel Worksheet using Word VBA

With an already-opened workbook, I want to create a copy of a worksheet ("Template") and re-name it with the value I have in an array. 对于一个已经打开的工作簿,我想创建一个工作表(“模板”)的副本,并使用数组中的值重新命名它。 When I debug the code the copy is created when I execute the line but I still get an error 424: object required. 当我调试代码时,在执行该行时就创建了副本,但仍然出现错误424:object required。

I've tried On Error Resume Next but since I already used On Error GoTo in my sub it isn't read. 我已经尝试过On Error Resume Next,但是由于我已经在子菜单中使用On Error GoTo,因此无法读取。

Dim oXL As Excel.Application 'Requires loading "Microsoft Excel 16.0 Object Library" from Tools -> References
Dim oWB As Excel.Workbook

Set oXL = New Excel.Application
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel
oXL.Visible = True 'Shows Excel window while running code. Set to false after finished editing.

Dim ws As Worksheet
For i = LBound(seller_names) To UBound(seller_names)
    'On Error Resume Next 'Doesn't work
    Set ws = oXL.ActiveWorkbook.Sheets("Template").Copy(After:= _
             oXL.ActiveWorkbook.Sheets(oXL.ActiveWorkbook.Sheets.Count))
    ws.name = seller_names(i)
Next i

Sheets.Copy doesn't return a reference to the copied sheet, so you need to first copy the sheet, then get a reference to it: Sheets.Copy不会返回对已复制图纸的引用,因此您需要先复制该图纸,然后再获取对其的引用:

With oXL.ActiveWorkbook
    .Sheets("Template").Copy After:= .Sheets(.Sheets.Count)
    Set ws = .Sheets(.Sheets.Count)) '<< get the copy
    ws.name = seller_names(i)
End With

On Error Resume Next should always work - but is not always a good solution - unless you have "Break on all errors" enabled in your VBA Options. On Error Resume Next ,除非您在VBA选项中启用了“打破所有错误”,否则On Error Resume Next应该始终可以工作-但并非总是一个好的解决方案。

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

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