VBA - Add sheets to variable and move to new workbook

眉间皱痕 提交于 2020-01-06 11:49:51

问题


I am trying to write a macro which can create up to 3 new worksheets, and at the end will move those sheets to a new workbook. Some, all or none of those sheets may be created, and I am struggling to move them all. I have tried adding their names to both a string and an array (with and without quotes to mimic if I manually typed the names of the sheets to move).

This is what I have at the moment, but it is returning Run-Time error '9': Subscript out of range. If I only move one of the sheets this works fine, but as soon as there are multiple sheets it stops working. Please could someone advise?

Dim SheetNames As String  

if x is True Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "a"
    SheetNames = Worksheet.Name
End if
if y is True Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "b"
    If SheetNames = "" Then
        SheetNames = Worksheet.Name
    Else
        SheetNames = sheetNames & Worksheet.Name
    End if
End if
if z is True Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "c"
    If SheetNames = "" Then
        SheetNames = Worksheet.Name
    Else
        SheetNames = sheetNames & Worksheet.Name
    End if
End if

Sheets(Array(SheetNames)).Move

回答1:


You can't pass a string holding all the sheet names inside the Array() call.

What you can do is to create an array to hold the name of the worksheets you want to move, and call the move method afterwards:

Sub example()

Dim x As Boolean, y As Boolean, z As Boolean

Dim SheetNamesArr() As String
Dim ArrSize As Integer

x = True
y = True
z = True

ArrSize = 0
ReDim Preserve SheetNamesArr(ArrSize)

If x Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "a"
    ReDim Preserve SheetNamesArr(0 To ArrSize)
    SheetNamesArr(ArrSize) = ActiveSheet.Name
    ArrSize = ArrSize + 1
End If

If y Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "b"
    ReDim Preserve SheetNamesArr(0 To ArrSize)
    SheetNamesArr(ArrSize) = ActiveSheet.Name
    ArrSize = ArrSize + 1
End If

If z Then
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "c"
    ReDim Preserve SheetNamesArr(0 To ArrSize)
    SheetNamesArr(ArrSize) = ActiveSheet.Name
    ArrSize = ArrSize + 1
End If

Sheets(SheetNamesArr).Move

End Sub


来源:https://stackoverflow.com/questions/52058318/vba-add-sheets-to-variable-and-move-to-new-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!