简体   繁体   English

类型不匹配错误Excel VBA

[英]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. 谢谢。

You could try the following code: (Place it in the code for ThisWorkbook ) 您可以尝试以下代码:(将其放入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. 一个警告-Workbook_Open事件有时是“有问题的”,因为它有时在所有Worksheets都完全加载之前触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM