使用InStr进行循环

时间:2014-12-18 10:52:53

标签: excel excel-vba vba

宏需要循环遍历可变数量的行(列A)并标记它们(在列B中)关于四个 InStr 搜索条件。

如果未满足四个条件,请创建一个空白标签并继续

我的代码看起来像这样,但无效。

Sub LabelMaker() 
Dim rng As Range 
Set rng = ActiveCell 

Do While
ActiveCell.Value <> Empty 
If InStr(1, rng, "search criterion 1") Then
     ActiveCell.Offset(0, 0).Select
     ActiveCell.Offset(0, 1).Value = "Label 1" 
     ElseIf InStr(1, rng, "search criterion 2") Then
     ActiveCell.Offset(0, 0).Select
     ActiveCell.Offset(0, 1).Value = "Label 2"

....等等

End If 
Set rng = rng.Offset(1, 0) 
Loop 
End Sub

1 个答案:

答案 0 :(得分:1)

这对你有用吗?我已经使用了EngJon的LastRow建议,并将其放入一个工作小组中。

Sub MakeLabels()

    Dim lastRow As Long
    Dim cl As Range

     Const dataCol As Long = 1

    lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

    For Each cl In ActiveSheet.Range(Cells(2, dataCol), Cells(lastRow, dataCol))

        If InStr(1, cl.Value, "Search Crterion 1") Then
            cl.Offset(0, 1).Value = "Label 1"
        ElseIf InStr(1, cl, "Search Crterion 2") Then
            cl.Offset(0, 1).Value = "Label 2"
        Else
            cl.Offset(0, 1).Value = "Blank Label"
        End If

    Next cl


    End Sub