将macros从创build新工作簿更改为引用模板

除了一件事外,我已经制定了一个完全适合我的需求的macros。 目前它为我创build没有格式的新工作簿。 我想改变它,以便它引用一个模板并使用该格式。

我一直在搞"Set wbDest = Workbooks.Add(xlWBATWorksheet)"行,但似乎无法得到任何工作!

 Private Sub CommandButton1_Click() Const sColumn As String = "M" Dim wbDest As Workbook Dim rngFilter As Range, rngUniques As Range Dim cell As Range Set rngFilter = Range(sColumn & "1", Range(sColumn & Rows.Count).End(xlUp)) Application.ScreenUpdating = False With rngFilter .AdvancedFilter Action:=xlFilterInPlace, Unique:=True Set rngUniques = Range(sColumn & "2", Range(sColumn & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible) On Error Resume Next ActiveSheet.ShowAllData On Error GoTo 0 End With For Each cell In rngUniques Set wbDest = Workbooks.Add(xlWBATWorksheet) rngFilter.AutoFilter Field:=1, Criteria1:=cell.Value rngFilter.EntireRow.Copy With wbDest.Sheets(1).Range("A1") .PasteSpecial xlPasteColumnWidths .PasteSpecial xlPasteValuesAndNumberFormats End With Application.CutCopyMode = True wbDest.Sheets(1).Name = cell.Value Application.DisplayAlerts = False wbDest.SaveAs ThisWorkbook.Path & Application.PathSeparator & cell.Value & " " & Format(DateSerial(Year(Date), Month(Date) - 1, 1), "mm-yy") wbDest.Close False Application.DisplayAlerts = True Next cell rngFilter.Parent.AutoFilterMode = False Application.ScreenUpdating = True End Sub 

`

Workbooks.Add()接受一个参数 – 模板。 因此,创build一个模板,将其保存为.xltx文件,然后使用该文件path添加新的工作簿:

 Dim wb As Workbook Dim filepath As String filepath = "C:\template.xltx" 'Or what-ever... Set wb = Application.Workbooks.Add(filepath) With wb '... End With 

怎么样..

 Dim wbTemplate As Workbook Set wbTemplate = Workbooks.Open("C:\mytemplate.xlsx") 

其中mytemplate.xlsx是您的预格式化模板。 我将它分配给一个variables对象的原因是因为它看起来像需要引用它才能将数据input到模板中。 如果你只是试图打开一个工作簿,下面的一行可以接受..

 Workbooks.Open("C:\mytemplate.xlsx")