PDA

View Full Version : Runtime error in macro



prabhadixit
06-16-2008, 08:15 AM
I have a piece of code that reads values from a database (a Excel worksheet) and displays values on a form (also a Excel worksheet). If the values of certain cells are 0 then those rows must be hidden. This piece of code is triggered every time the value in cell C5 of the form is changed, using Sub Worksheet_Change. If a non-existent value is input in C5 then all the values in the form turn blank and this is achieved using IF(ISNA...) in the vlookup function.
My code works perfectly when a correct value is input in C5. However, when a wrong value is input in C5 it results in a run-time error. Here is a sample of my code.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim j As String
If Target.Address = "$C$5" Then
Range("E21").Select
ActiveCell.FormulaR1C1 = _
"=IF(ISNA(VLOOKUP(R[-16]C[-2],'dif comp y ajuste de sueldo'!R [-17]C[-3]:R[98]C[117],42,FALSE)),"""",VLOOKUP(R[-16]C[-2],'dif comp y ajuste de sueldo'!R[-17]C[-3]:R[98]C[117],42,FALSE))"
Range("E22").Select
ActiveCell.FormulaR1C1 = _
"=IF(ISNA(VLOOKUP(R[-17]C[-2],'dif comp y ajuste de sueldo'!R[-18]C[-3]:R[99]C[117],43,FALSE)),"""",VLOOKUP(R[-17]C[-2],'dif comp y ajuste de sueldo'!R[-18]C[-3]:R[99]C[117],43,FALSE))"
Range("E21").Select
j = ActiveCell.Value
If j = 0 Then OR j = """"
Rows("21:21").Select
Selection.EntireRow.Hidden = True
End If
End If
End Sub
When cell C5 has a non-existent value input, the cells E21 and E22 turn blank but result in a run timer error in statement ?j = ActiveCell.Value? or in the statement ?If j = 0?.
Can someone help?

grichey
06-16-2008, 08:20 AM
First, USE VBA TAGS!! secondly, try setting it to if if (or(J=0,J=""))

grichey
06-16-2008, 08:21 AM
edit: double post

Bob Phillips
06-16-2008, 09:08 AM
Private Sub Worksheet_Change(ByVal Target As Range)
Dim j As String
Dim sLookup As String
If Target.Address = "$C$5" Then
sLookup = "VLOOKUP(R[-16]C[-2],'dif comp y ajuste de sueldo'!R[-17]C[-3]:R[98]C[117],42,FALSE)"
Range("E21").FormulaR1C1 = "=IF(ISNA(" & sLookup & "),""""," & sLookup & ")"
sLookup = "VLOOKUP(R[-17]C[-2],'dif comp y ajuste de sueldo'!R[-18]C[-3]:R[99]C[117],43,FALSE)"
Range("E22").FormulaR1C1 = "=IF(ISNA(" & sLookup & "),""""," & sLookup & ")"
j = Range("E21").Value
If j = 0 Or j = "" Then
Rows(21).Hidden = True
End If
End If
End Sub