删除工作表后不保存值的数组变量

时间:2021-02-15 09:24:47

Can someone explain why this happens? I have an array variable Loans() that stores several short strings that I need to use later for formatting a pivot table. The values get stored from the "Fund List" sheet. Then the sheet gets deleted, but I still need to use the values. Excel returns an object required error when I try to use the Loans() variable after the sheet is deleted. I have found the way around this is to not delete the sheet, but does anyone know why this is? The relevant code is below.

有人能解释为什么会这样吗?我有一个数组变量Loans(),它存储了几个我需要稍后用于格式化数据透视表的短字符串。值从“基金清单”表中存储。然后页面被删除,但我仍然需要使用这些值。当我在删除工作表后尝试使用Loans()变量时,Excel返回一个对象必需的错误。我发现解决这个问题的方法是不删除工作表,但有谁知道这是为什么?相关代码如下。

Sheets("Fund List").Select

    ' some code

Dim Loans() As Variant
Dim index As Integer
If LN > 0 Then
    ReDim Loans(LN - 1)
    index = 0
    For i = 1 To LastRow
        If Range("H" & i).Value = 3 Then
            Set Loans(index) = Range("A" & i)
            index = index + 1
        End If
    Next i
End If

    ' some more code

Sheets("Fund List").Delete

    ' more code

Set objField = objTable.PivotFields("Fund")
If LN > 0 Then
    For index = 0 To UBound(Loans)
        ' I get an object required error on the following line:
        LNFund = Loans(index)
        objField.PivotItems(LNFund).Visible = False
    Next index
End If

1 个解决方案

#1


6  

You are setting the variant array elements to the Range object.

您正在将变量数组元素设置为Range对象。

Set Loans(index) = Range("A" & i)

Assign the Range.Value or Range.Value2 property instead.

改为分配Range.Value或Range.Value2属性。

Loans(index) = Range("A" & i).Value2

Note not Set.

注意没有设置。

#1


6  

You are setting the variant array elements to the Range object.

您正在将变量数组元素设置为Range对象。

Set Loans(index) = Range("A" & i)

Assign the Range.Value or Range.Value2 property instead.

改为分配Range.Value或Range.Value2属性。

Loans(index) = Range("A" & i).Value2

Note not Set.

注意没有设置。