简体   繁体   中英

conditional statement within for loop

The following code is for a dropdown list in E7 that is dependent on a the value in a specific cell (Pos_Cat). The idea is to loop through column E of the other sheet looking for values that match Pos_Cat and add the value of column H in that row to a string, which is my formula for the dropdown list.

The code worked fine when I was adding all of the values in the range, but when the conditional statement was added it began to throw an error for "AStr = Right(AStr, Len(AStr) - 1)".

Thank you for your help!

If Not Intersect(Target, Range("E7")) Is Nothing Then

Dim PTMsht As Worksheet
    Set PTMsht = Sheets("PTM")
Dim TRNsht As Worksheet
    Set TRNsht = Sheets("TL")
Dim Pos_Cat As String
    Pos_Cat = TRNsht.Range("E6").Value
Dim Lrow As Single
    Lrow = PTMsht.Range("E" & Rows.Count).End(xlUp).Row
Dim AStr As String

Dim i As Long

For Each cell In PTMsht.Range("H15:H100")
    If cell.Offset(0, -3).Value = Pos_Cat Then
        AStr = AStr & "," & cell
    End If
Next
           AStr = Right(AStr, Len(AStr) - 1)

With TRNsht.Range("E7").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:=AStr
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With
End If

When AStr is blank this will error out (see explination as to why below) . If AStr should never be a blank string then you need to check your upstream logic. If you sometimes expect AStr to return a blank value you need to account for that with something like this:

If Len(AStr) > 0 Then
    AStr = Right(AStr, Len(AStr) - 1)
Else
    MsgBox "AStr is blank string"
    'Do something here when you get blank string
End If

The Error

When your string is blank this is how your expression evaluates

AStr = Right(AStr, 0 -1) = Right(AStr, -1)

The Right function only takes positive values which is the source of your error. You are asking for the function to return the negative first character which is non-sensible.

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