我制作了一个完全符合我需求的宏,除了一件事。目前它为我创建了没有格式的新工作簿。我想更改它,以便它引用模板并使用该格式。
我一直在搞乱 "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
`
答案 0 :(得分:1)
Workbooks.Add()
接受一个参数 - 模板。因此,创建一个模板,将其另存为.xltx文件,然后使用该文件路径添加新工作簿:
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
答案 1 :(得分:0)
怎么样..
Dim wbTemplate As Workbook
Set wbTemplate = Workbooks.Open("C:\mytemplate.xlsx")
mytemplate.xlsx是您预先格式化的模板。我将其分配给变量对象的原因是因为看起来您需要引用它才能将数据输入到模板中。如果您只是尝试打开工作簿,则可以使用下面的单行代码。
Workbooks.Open("C:\mytemplate.xlsx")