VBA Button为新工作簿创建新工作表

时间:2017-03-09 16:07:11

标签: excel vba excel-vba excel-2010

在下面的代码中,我在用户表单上有一个按钮,从模板创建一个新工作表,重命名并在新工作簿和当前工作簿中打开它。反正有没有自动化,所以它不会在当前工作簿和新工作簿中创建新工作表?此外,它每次创建一个新的工作簿,无论如何,创建所有新工作表时创建保存到一个工作簿?什么都有帮助,谢谢!

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

2 个答案:

答案 0 :(得分:1)

您可以按如下方式调整代码:

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

答案 1 :(得分:0)

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

Public newWB as Workbook

然后,您的用户表单代码就是这样(您需要使用附加代码进行修改,因为我没有提供您的工作表结构和数据):

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变量的Module1.newWB方法创建新工作簿,并且此变量将一直存在,直到您关闭文件或VBA运行时中存在状态丢失(即,您中止或终止运行时的未处理异常等。)。