简体   繁体   中英

How do I create a worksheet from a stored worksheet variable

new VBA user here...

I don't know how to create a worksheet from a variable stored in memory. What I'm trying to do is create multiple copies of an existing "template" sheet from the open workbook, manipulate them in memory (eg change range values, add formulas, etc.) and then create them in the open workbook as actual sheets.

I can create the copies in memory and store them in an array, but I cannot then create the actual worksheet in my workbook. Help please :)

Dim wb As Workbook
Dim ws As Worksheet
Dim wsTemplate As Worksheet
Dim wsCopies(1 To 5) As Worksheet
Dim x As Long

Set wb = ThisWorkbook
Set ws = wb.Sheets("Worksheet Test")
Set wsCopy = ws


For x = 1 To 5
    Set wsCopies(x) = wsTemplate
'used this line to make sure this actually copied into memory
    Debug.Print wsCopies(x).Range("A1").FormulaR1C1
Next x

Thanks in advance!

There really isn't a "Worksheet in memory" that only exists in memory. You create a new worksheet, and there it is, in your workbook. There's also not a great way to duplicate a worksheet without a little trickery. Something like:

For x = 1 To 5
    wsTemplate.copy after:=wsTemplate
    Set wsCopies(x) = wb.Sheets(wsTemplate.index + 1)
'used this line to make sure this actually copied into memory
    Debug.Print wsCopies(x).Range("A1").FormulaR1C1
Next x

Which isn't terrible, but it's not exactly what you were thinking. If you aren't into application.screenupdating = false and all that, you could set the wsCopies(x).visible to xlSheetHidden and do your further manipulation until you toggle to visible again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM