簡體   English   中英

Excel VBA:根據單元格值插入N個表單

[英]Excel VBA: Insert N number of Sheets based on cell value

我是Excel VBA的新手。 我想根據單元格值插入單元格數。

我有sheet1,我想使用b4作為要插入的工作表數量(這是一個模板)的參考。

例如,如果b4 = 4的值,我想復制模板表4次。

我怎么在vba中這樣做?

謝謝。 :)

沒有魔法,在循環中逐個創建它們,將每個新的放在最后。 編輯:您還想將它們重命名為1,2,3,4,..所以:

Sub CreateSheets()
    Dim i As Long
    With ThisWorkbook.Sheets
      For i = 1 To Sheet1.Range("B4").Value2
        .Item("Template").Copy After:=.Item(.Count)
        .Item(.Count).Name = i
      Next
    End With
End Sub

這樣的事情應該有效:

Sub copySheets()

Dim i As integer

Dim n As integer 'the amount of sheets

n = Cells(4, 2).Value 'b4

For i = 2 To n
    If ActiveWorkbooks.Worksheets.Count < n Then 'Makes sure the sheets exists
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    End If
    ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'copy data

Next i

End Sub

或類似的東西......

Sub CopyTemplate()
Dim ws As Worksheet, wsTemplate As Worksheet
Dim n As Integer, i As Long
Application.ScreenUpdating = False
Set ws = Sheets("Sheet1")
Set wsTemplate = Sheets("Template")     'Where Template is the name of Template Sheet, change it as required.
n = ws.Range("B4").Value
If n > 0 Then
    For i = 1 To n
        wsTemplate.Copy after:=Sheets(Sheets.Count)
        ActiveSheet.Name = i
    Next i
End If
Application.ScreenUpdating = True
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM