从选定的工作表中保存新工作簿

时间:2016-10-28 05:48:17

标签: excel vba excel-vba checkbox

所以我的主要目标是将工作表(取决于它们是否由首页上的复选框选中)保存到新工作簿。

我有6张,所以我的首页/表格上有6个不同的复选框。

这是我尝试过的示例代码(注意:这只显示了1个复选框的检查,但我需要6个复选框):

Sub saveSheetWorkbook()

Dim exampleName As Variant
Dim exampleSavePath As String
Dim exampleSheet As Variant

exampleName = InputBox("Who will this be sent to?")

exampleSavePath = ActiveWorkbook.Path & "\" & exampleName

If Worksheets("Example Worksheet 1").Range("E29") = True Then
exampleSheet = "Example Worksheet 2"
End If

Sheets(Array("Example Worksheet 1"), exampleSheet).Copy
ActiveWorkbook.SaveAs Filename:=exampleSavePath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

End Sub

例如,我想始终保存示例工作表1,但是如果勾选了复选框,则只保存示例工作表2(和3,4,5,6)。示例工作表1中的单元格E29是复选框的链接单元格。

因此勾选复选框时此宏工作,但当未选中复选框时,我收到错误。

我已将其设置为使得表单数组包含名称或任何内容。但是什么时候什么也没有,这给了我错误。

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

替换它:

If Worksheets("Example Worksheet 1").Range("E29") = True Then
    exampleSheet = "Example Worksheet 2"
End If
Sheets(Array("Example Worksheet 1"), exampleSheet).Copy

有了这个:

If Worksheets("Example Worksheet 1").Range("E29") = True Then
    exampleSheet = "Example Worksheet 2"
    Sheets(Array("Example Worksheet 1", exampleSheet)).Copy
Else
    Sheets("Example Worksheet 1").Copy
End If

答案 1 :(得分:0)

你可能想表现如下(见评论):

Option Explicit

Sub saveSheetWorkbook()
    Dim exampleSavePath As String
    Dim sheetsArr As Variant, linkedCellsArr As Variant
    Dim toBeCopiedSheetsNames As String
    Dim iElem As Long

    linkedCellsArr = Array("E29", "E30", "E31") '<--| list your linked cells addresses
    sheetsArr = Array("Example Worksheet 2", "Example Worksheet 3", "Example Worksheet 4") '<--| list your worksheets in corresponding order to linkedcells

    toBeCopiedSheetsNames = "Example Worksheet 1" '<--| put "Example Worksheet 1" worksheet in the worksheets to be copied list for sure
    For iElem = LBound(linkedCellsArr) To UBound(linkedCellsArr) '<--| loop through linked cells (addresses array)
        If Range(linkedCellsArr(iElem)) Then toBeCopiedSheetsNames = toBeCopiedSheetsNames & "|" & sheetsArr(iElem) '<-- if TRUE then add corresponding worksheet name to the worksheet to be copied list
    Next iElem

    exampleSavePath = ActiveWorkbook.Path & "\" & Application.InputBox("Who will this be sent to?", Type:=2) '<--| retrieve the file name and build its "full" name

    Sheets(Split(toBeCopiedSheetsNames, "|")).Copy '<--| copy worksheets whose name is listed in 'toBeCopiedSheetsNames'
    ActiveWorkbook.SaveAs Filename:=exampleSavePath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub