VBAbutton创build新工作簿到新的工作簿

在下面的代码中,我在用户表单上有一个button,从模板中创build一个新工作表,将其重命名并在新工作簿以及当前工作簿中打开它。 是否有自动化,所以它不会在当前的工作簿中创build新的工作表,只是新的工作簿? 它也创build一个新的工作簿,无论如何,创build新的工作表创build时保存到一个工作簿? 任何帮助,谢谢!

Private Sub btnSave_Click() Dim LastRow As Long, ws As Worksheet Set ws = Sheets("Employee Information") LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 If Me.cbStores.Value = "Northern / Northmart" Then Dim newWB as Workbook Dim thisWB as Workbook Set thisWB = ThisWorkbook set newWB = Application.Workbooks.Add thisWB.Sheets("TEMPLATE").Copy after:=newWB.Sheets("Sheet1") set sh = newWB.Sheets("TEMPLATE") ' Naming and hyperlink to 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" EndIf End Sub 

你可以调整你的代码如下:

  Set newWB = GetOrCreateWB("NewWb", "C:\Users\....\MyFolder") '<--| try getting the already open "NewWb" workbook or opening it from given folder ore create it in given folder thisWB.Sheets("TEMPLATE").Copy after:=newWB.Sheets(1) With ActiveSheet '<--| the just pasted worksheet becomes the active one .Name = AddEmployeeUF.txtFirstname.Text + AddEmployeeUF.txtMiddleinitial.Text + AddEmployeeUF.txtLastname.Text + "Template" '<--| Name it ws.Hyperlinks.Add Anchor:=ws.Range("F" & LastRow), Address:="", SubAddress:=.Name & "!A1", TextToDisplay:="View" '<--| hyperlink to new sheet End With Next i 

它开发了以下function:

 Function GetOrCreateWB(wbName As String, wbPath As String) As Workbook On Error Resume Next Set GetOrCreateWB = Workbooks(wbName) If GetOrCreateWB Is Nothing Then Set GetOrCreateWB = Workbooks.Open(wbPath & "\" & wbName) If GetOrCreateWB Is Nothing Then Set GetOrCreateWB = Workbooks.Add GetOrCreateWB.SaveAs Filename:=wbPath & "\" & wbName End If End If End Function 

在普通的代码模块(不在UserForm代码模块中), 在模块顶部的任何过程之外执行此操作:

 Public newWB as Workbook 

然后,你的userform代码就像这样(因为我没有你的工作表结构和数据可用),所以你需要修改你的代码。

 Private Sub btnSave_Click() Dim sh As Worksheet Dim thisWB As Workbook Set thisWB = ThisWorkbook If Module1.newWB Is Nothing Then Set Module1.newWB = Workbooks.Add End If thisWB.Sheets("TEMPLATE").Copy after:=newWB.Sheets(newWB.Sheets.Count) Set sh = Module1.newWB.Sheets("TEMPLATE") ' Naming and hyperlink to new sheet 'sh.Name = AddEmployeeUF.txtFirstname.Text + AddEmployeeUF.txtMiddleinitial.Text + AddEmployeeUF.txtLastname.Text + "Template" 'This line raises an error because "ws" is not declared 'ws.Hyperlinks.Add Anchor:=ws.Range("F" & LastRow), Address:="", SubAddress:=sh.Name & "!A1", TextToDisplay:="View" End Sub 

您第一次运行此代码时, Module1.newWB是没有,它没有被分配任何对象值。 因此,使用Workbooks.Add方法创build一个新的工作Workbooks.Add ,该方法分配给Module1.newWBvariables,并且此variables一直存在,直到您closures该文件,或者在VBA运行时中存在状态丢失(即,未处理的exception中止或终止运行时等)。