将使用列表框的代码替换为使用Y / N表的代码

时间:2014-10-22 18:30:11

标签: excel vba excel-vba

所以之前,我的代码运行了所有已检查的状态。现在,我必须用一列状态和一列Y / N替换列表框。我希望代码能够运行在它们旁边有Y的所有状态。

之前的代码:

For Item = 0 To Sheets("Documentation").ListBox1.ListCount - 1
    If Sheets("Documentation").ListBox1.Selected(Item) = True Then
        If Sheets("Documentation").ListBox1.List(Item) = "Compact" Then
            Range("Statename") = "CO"
            stname = "C"
        Else
            Range("Statename") = Sheets("Documentation").ListBox1.List(Item)
            stname = Range("Statename")
        End If
        ....
        ....
        ....
     End If
Next

我不确定如何将其作为for循环。我的尝试:

For cell in range(Range of Y/N Column)
     If Range(cell) = "Y"  Then
         If Range("rowofcell,columnofcell - 1") = "Compact" Then
                Range("Statename") = "CO"
                stname = "C"
            Else
                Range("Statename") = Range("rowofcell,columnofcell - 1")
                stname = Range("Statename")
            End If
            ....
            ....
            ....
         End If
    Next

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

由于您未提及数据的位置以及输出的使用方式,因此我获得了一点创意许可。从这样的数据开始:

enter image description here


运行此宏:

Sub loopList()
    Dim cell As Range
    Dim StateName As Range
    Dim stname As String

    For Each cell In Range("B2:B8")
        If cell.Value = "Y" Then
            Set StateName = Cells(cell.Row, cell.Column + 1)

            If cell.Offset(0, -1) = "Compact" Then
                StateName.Value = "CO"
                stname = "C"
            Else
                StateName = cell.Offset(0, -1)
                stname = StateName.Value
            End If
         End If
    Next
End Sub

输出:

enter image description here