Excel VBA循环遍历循环内对象名称的字符串数组

时间:2017-11-26 17:07:47

标签: arrays excel-vba object vba excel

我想使用一个字符串数组来替换我循环中的Worksheet对象,但我似乎无法弄明白。

如果我将SheetX声明为Variant,那么我会得到Object Required Error

如果我将SheetX声明为Object,那么我会得到编译错误:For Array上的每个变量都必须是变量

Sub DeleteAllData()

'SheetsArray = ["BalanceSheetTransposed", "IncomeStatementTransposed", "CashflowStatement"]
Dim SheetsArray(0 To 2) As Variant
Dim SheetX As Object

SheetsArray(0) = "BalanceSheetTransposed"
SheetsArray(1) = "IncomeStatementTransposed"
SheetsArray(2) = "CashflowStatement"

For Each SheetX In SheetsArray
    lastrow = SheetX.Cells(Rows.Count, 1).End(xlUp).Row
    lastcolumn = SheetX.Cells(1, Columns.Count).End(xlToLeft).Column
    SheetX.Range("A2", Cells(lastrow, lastcolumn)).ClearContents
Next SheetX

End Sub

3 个答案:

答案 0 :(得分:1)

您的主要问题是您试图将存储在数组中的字符串视为工作表,但它们只是字符串。

最简单的解决方法是使用Worksheets(SheetsArray)返回包含您要使用的名称的工作表,然后循环遍历这些工作表:

Sub DeleteAllData()

    Dim SheetX As Worksheet
    Dim lastRow As Long
    Dim lastColumn As Long

    Dim SheetsArray(0 To 2) As Variant
    SheetsArray(0) = "BalanceSheetTransposed"
    SheetsArray(1) = "IncomeStatementTransposed"
    SheetsArray(2) = "CashflowStatement"
    'An alternative to the previous 4 lines would be
    'Dim SheetsArray As Variant
    'SheetsArray = Array("BalanceSheetTransposed", _
    '                    "IncomeStatementTransposed", _
    '                    "CashflowStatement")

    'Loop through the worksheets referred to in the array
    For Each SheetX In Worksheets(SheetsArray)

        With SheetX  ' avoids some typing
            lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

            'Existing code would have had issue with the unqualified Cells
            'reference in the following line.  You should always qualify Cells
            'to specify which sheet you mean, because it defaults to
            'ActiveSheet.Cells
            .Range("A2", .Cells(lastRow, lastColumn)).ClearContents
        End With

    Next SheetX

End Sub

答案 1 :(得分:0)

出于我的想法,因为我在这台机器上没有Excel。遍历字符串并设置工作表对象。

<style type="text/css">
    .container{
        margin: 0 auto;
        width: 210px;
    }
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    }
    .form input{
        display: inline-block;
        text-align: left;
        float: right;
    }
</style>

答案 2 :(得分:0)

必须将Array传递给Sheets object

Sub DeleteAllData()
    Dim ws As Worksheet

    For Each ws In Sheets(Array("BalanceSheetTransposed", "IncomeStatementTransposed", _ 
                                                          "CashflowStatement"))
        s.UsedRange.Offset(1).ClearContents
    Next
End Sub