Excel VBA创建工作簿并使用工作表填充

时间:2017-09-18 11:33:18

标签: excel-vba vba excel

(Excel 2007)

我有两段代码。

创建并保存新的Excel工作簿:

Sub NewWorkBook()

Set NewBook = Workbooks.Add
   With NewBook
   .SaveAs Filename:="NewBook.xlsx"
   End With

End Sub

另一个创建工作表:

Public Sub CreateWorksheets()

Dim n As Integer
n = 1
Dim WrkSheet As Worksheet
For n = 1 To 31
  If n > Worksheets.Count Then
  Set WrkSheet = Sheets.Add(After:=Sheets(Worksheets.Count))
  Else
  Set WrkSheet = Sheets(Worksheets.Count)
  End If
WrkSheet.Name = n
Next n
End Sub

我需要使用这些来创建工作簿B'并使用工作表填充它,但所有代码必须从'工作簿A'运行。

我可以获得第一个创建工作簿的子工作,但是CreateWorksheets子工作只能在包含代码的工作簿上工作 - 然后只有我删除了除一个工作表之外的所有工作簿。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

 Sub NewWorkBookAndSheets()
 Dim NewBook As Workbook
 Dim n As Integer
 Dim start As Integer

 Set NewBook = Workbooks.Add
 With NewBook
     start = .Worksheets.Count + 1
     if start < 31 then 

     For n = start  To 31
          .Sheets.Add After:=Sheets(n - 1)
     Next n
     For n = 1 To 31
        .Worksheets(n).Name = n
     Next n
     end if
    .SaveAs Filename:="NewBook.xlsx"
 End With

 End Sub