【问题标题】:User form button create sheet on different workbook用户表单按钮在不同的工作簿上创建工作表
【发布时间】:2017-03-10 05:34:28
【问题描述】:

我是 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

【问题讨论】:

  • Sheets("Template").Copy after:=Sheets("Template") 告诉它将工作表放在工作表“模板”之后的同一工作簿中。尝试 wb = Workbooks.Add 使用 Sheets("Template").Copy before:=wb.Sheets(1) 使其成为新工作簿的第一个选项卡。

标签: vba excel excel-2010


【解决方案1】:

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

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

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() 可以引用未嵌入工作表或嵌入工作表的图表。我使用工作表()。它更具体并限制了出错的可能性。

【讨论】:

  • 子或函数未定义。 set wbk_dest = Workbook("目标工作簿")
  • 您尝试将工作表添加到的工作簿的名称是什么?由于我不知道您尝试将复制的工作表添加到的工作簿的名称,因此您需要将“目标工作簿”替换为您将工作表复制到的工作簿的名称。
  • 是的,我试过了,似乎不起作用。给我上面列出的错误。
  • 抱歉错字,应该是 Workbooks("Destination Workbook")
  • 下标超出范围错误集 wbk_dest = Workbooks("Destination Workbook")
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多