简体   繁体   中英

Excel Type MisMatch with VBA to hide certain rows

I realize there are already a number of great responses for dealing with VBA TypeMismatch errors in Excel, but they all seem quite case-specific and I'm admittedly too much of a VBA n00b to follow them.

So, I wondered if you might be able to help me with this specific predicament: I have made up a workbook and I want rows to automatically hide themselves if the value in column C is less than today's date. * I assigned the following Macro to an ActiveX Command Button: *


Sub Hide_PastOrders()
 Dim MyRange As Range, C As Range
 Application.ScreenUpdating = False
 Application.Calculation = xlCalculationManual
 Set MyRange = Range("d1:d1000")
 MyRange.EntireRow.Hidden = False
 For Each C In MyRange
     If IsDate(C.Value) And C.Value < Date Then
         C.EntireRow.Hidden = True
     End If
 Next
 Application.ScreenUpdating = True
 Application.Calculation = xlCalculationAutomatic
 End Sub

It was working fine until recently, but now sometimes results in a 'Type MisMatch' and I'm not sure why. It only seems to be an issue on a couple of the worksheets and they are all assigned the same macro.

I have also implemented an ActiveX command button to 'Show all rows':


Sub ShowAll_Click()
ActiveSheet.Cells.EntireRow.Hidden = False
End Sub

Haven't had any issues with this one.

Also, I'm not sure that this is relevant, but I have created a number of internal references in my document. ie typed "=A5" in B5 for example so that if there are changes to our rentals for multiple pieces of equipment, I would only have to type the information in once. This proves to be very frustrating because everytime I encounter a 'TypeMismatch' Error, it reverts certain cells to "=REF".

Please let me know if I'm taking the wrong approach or if you have any suggestions!

Thanks, Alexandra.

The expression in the if statement is not short-circuited in VBA. Try this:

If IsDate(C.Value) Then
     If  C.Value < Date Then
         C.EntireRow.Hidden = True
     End If
End If

See http://en.m.wikipedia.org/wiki/Short-circuit_evaluation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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