HK1
HK1

Reputation: 12210

Copy FormatCondition Object From Custom Collection

I know I'm probably trying to do something sort of abnormal. I need to save (and delete) all FormatCondition objects from a Controls FormatConditions collection. And then later I need to recreate/reapply those same FormatCondition objects back to the same control again.

It seems I can copy them successfully but I get errors when I try to reapply those same FormatCondition objects from my own Collection object. I suspect that what's happening here is that I'm not actually copying the objects in my SaveAndDelete routine as I think I am. And if that's the case, how can I go about actually cloning these objects so they persist after I run f.Delete?

Private SavedFC As New Collection

Private Sub SaveAndDeleteFormatConditions(c as Control)
    Dim f As FormatCondition
    For Each f In c.FormatConditions
        SavedFC.Add f
        f.Delete
    Next
End Sub

Private Sub RecreateFormatConditions(c as control)
    Dim i As Integer
    i = 1
    If SavedFC.Count > 0 Then
        Dim f1 As FormatCondition, f2 As FormatCondition
        For Each f1 In SavedFC

            'Error 2467 occurs here: The expression you entered refers to an object that is closed or doesn't exist
            Set f2 = c.FormatConditions.Add(f1.Type, f1.Operator, f1.Expression1, f1.Expression2)
            With f2
                .BackColor = f1.BackColor
                .FontBold = f1.FontBold
                .FontItalic = f1.FontItalic
                .FontUnderline = f1.FontUnderline
                .ForeColor = f1.ForeColor
            End With
            SavedFC(i).Delete
            i = i + 1
        Next
    End If
End Sub

Upvotes: 1

Views: 654

Answers (1)

Igor Turman
Igor Turman

Reputation: 2205

This line causes the problem:

f.Delete

What happens here is you add an item to the collection (it is an object, so you operate with the reference). Then, you delete the object itself. Now, you have a collection of pointers that point to the deleted/non-existent objects. That's why you get 2467 error later.

Upvotes: 1

Related Questions