用户表单按钮在不同的工作簿上创建工作表

时间:2017-03-09 19:39:40

标签: excel vba excel-vba excel-2010

我是Excel的新手,所以我希望这是有道理的。下面的代码是基于模板创建新工作表,并在单击用户表单上的按钮后重命名。我尝试在另一个现有工作簿中打开正在创建的工作表,但超链接仍然有效。有关如何实现这一目标的任何想法?什么都有帮助,谢谢。

If Me.cbStores.Value = "Northern" Then
Sheets("Template").Copy after:=Sheets("Template")
Set sh = ActiveSheet
' Do whatever you have to do with the new sheet
sh.Name = AddEmployeeUF.txtFirstname.Text + AddEmployeeUF.txtMiddleinitial.Text + AddEmployeeUF.txtLastname.Text + "Template"
ws.Hyperlinks.Add Anchor:=ws.Range("F" & LastRow), Address:="", SubAddress:=sh.Name & "!A1", TextToDisplay:="View"
End If

1 个答案:

答案 0 :(得分:0)

您似乎正在将工作表“模板”复制到当前工作簿。

试试这个,看看它是如何工作的,如果你收到错误就告诉我。

If Me.cbStores.Value = "Northern" Then
    ' create objects
    dim wbk_dest as Workbook
    dim wks_copy as Worksheet

    ' initialize objects
    set wbk_dest = Workbooks("Destination Workbook")

    ' copies template worksheet to destination workbook and places the 
    ' the worksheet in the first position; you can place it anywhere
    Worksheets("Template").Copy before:=wbk_dest.Worksheets(1)
    set wks_copy = wbk_dest.ActiveSheet

    ' Set sh = ActiveSheet

    ' Do whatever you have to do with the new sheet
    wks_copy.Name = AddEmployeeUF.txtFirstname.Text + _
                    AddEmployeeUF.txtMiddleinitial.Text + _ 
                    AddEmployeeUF.txtLastname.Text + "Template"

    ' what is "ws"?  is that a different worksheet?  the below statement
    ' looks like you are using a hyperlink to the newly copied worksheet.
    ' is that what you want to do?  As long as "ws" is visible you should be
    ' ok with this line
    ws.Hyperlinks.Add Anchor:=ws.Range("F" & LastRow), _
                      Address:="", SubAddress:=wks_copy.Name & "!A1", _ 
                      TextToDisplay:="View"

    ' clear object
    set wks_copy = Nothing
    set wbk_dest = Nothing
End If

提示

尽量避免使用Sheets()函数。 Sheets()可以引用未嵌入工作表或嵌入工作表中的图表。我使用Worksheets()。它更具体,并限制了出错的可能性。