juiceb0xk
juiceb0xk

Reputation: 969

Type mismatch error excel VBA

The goal of my code is to take the old value of a cell, and check it against a new value, if it is entered. And if the old value changes to a new value, then update the date in a cell specified.

The problem with my code is that I cannot seem to find a way to get around this error without my code breaking, thus I am having trouble trying to fix this one line of code. I have this code in two worksheets, both with their values altered for different cells. The problem is, this code DOES work only if it is for one worksheet, but when I use two with the same code, it throws a type mismatch error.

Here's my code:

Dim oldValue As Variant

Public Sub Worksheet_SelectionChange(ByVal Target As Range)
'My other worksheet is referencing cells E2:E100
oldValue = Me.Range("D4:D21").Value
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("D4:D21")) Is Nothing Then
Dim c As Range
For Each c In Intersect(Target, Me.Range("D4:D21"))
    'Check value against what is stored in "oldValue"
    'Type mismatch is on this line here
    If oldValue(c.Row - 3, 1) <> c.Value Then
        'Update value in column L (8 columns to the right of column D)
        c.Offset(0, 7).Value = Date 'or possibly "= Now()" if you need the time of day that the cell was updated
    End If
Next
End If
End Sub

I'm not sure what type mismatch error means, so I'm unable to fix this problem by myself. My question is, how can I properly update my cells without this mismatch error throwing?

EDIT: Keep in mind, one worksheet is looking for numeric data changes, and the other worksheet is looking for string value changes, I'm not sure if this matters. If I take out all the code for one worksheet, the code will work for the other, but when I put it back in, they both stop working.

Thank you.

Upvotes: 1

Views: 1001

Answers (1)

YowE3K
YowE3K

Reputation: 23974

You could try the following code: (Place it in the code for ThisWorkbook)

Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Dim ws As Worksheet
    Dim ws1 As Worksheet
    Set ws1 = ActiveSheet
    For Each ws In Worksheets
        ws.Activate
        ws.Range("A1").Select
    Next
    ws1.Activate
    Application.ScreenUpdating = True
End Sub

One warning - the Workbook_Open event is sometimes "problematic", as it occasionally fires before all the Worksheets are fully loaded.

Upvotes: 2

Related Questions