简体   繁体   English

Excel Vba-调用具有可变工作表名称的工作表

[英]Excel Vba - Calling a sheet with a variable sheet name

I've been coding in VBA for some time, but this one has really stumped me. 我已经在VBA中编码了一段时间了,但是这确实让我很头疼。

I'm creating a workbook which creates technical certificates for machines. 我正在创建一个工作簿,该工作簿为机器创建了技术证书。 We have varying templates depending on the machine type and I am attempting to get my code to select the correct sheet from a user input and then populate the sheet. 我们根据机器类型使用不同的模板,我正在尝试获取代码以从用户输入中选择正确的工作表,然后填充工作表。 FYI these template sheets will be hidden and the user can only interact with the userforms. 仅供参考,这些模板表将被隐藏,用户只能与用户表单进行交互。

Heres the code that is failing: 这是失败的代码:

Machine = MachineType.Text '<-- input from userform, for example Machine = "Vertex 251"

Set wsCopy = ThisWorkbook.Sheets(Machine) '<--- select that machine's sheet
wsCopy.Copy '<--Run time Error 1004: Method copy of object_worksheet failed

I've tried numerous different types including just sheets(machine).copy or 我尝试了多种不同的类型,包括sheets(machine).copy

Sheets(machine).activate
Activesheet.copy

but nothing has worked so far - I cannot tell if I am doing something fundamentally wrong. 但到目前为止,没有任何效果-我无法判断自己是否在做一些根本错误的事情。

Any help would be be appreciated. 任何帮助,将不胜感激。

Cheers. 干杯。

You must unhide the sheet before copying it (at least to a new workbook as lturner notes) - you can then re-hide it 您必须先取消隐藏工作表,然后再将其复制(至少要保留给新工作簿,如lturner所述)-然后可以重新隐藏工作表

Dim shtTemplate as Worksheet, sheetWasHidden As Boolean
Set shtTemplate = ThisWorkbook.Sheets(Machine)

'handle the case where the sheet to be copied is Hidden
If shtTemplate.Visible = xlSheetHidden Then
    shtTemplate.Visible = xlSheetVisible
     sheetWasHidden = True
End If

shtTemplate.Copy
If sheetWasHidden Then shtTemplate.Visible = xlSheetHidden 're-hide if needed

When you have the worksheet object and use the Copy method, Excel seems to be making assumptions (or not) about where you want to put the new sheet. 当您拥有工作表对象并使用Copy方法时,Excel似乎在假设(或不假设)您要放置新工作表的位置。 I pretty much always use the After option to define where the new sheet should go. 我几乎总是使用After选项来定义新工作表的位置。

Option Explicit

Sub test()
    Dim wsCopy As Worksheet
    Set wsCopy = ActiveSheet
    wsCopy.Copy After:=wsCopy
End Sub

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

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