在Excel VBA中单击按钮后切换单元格值

时间:2019-08-30 19:22:13

标签: excel vba

Image of first toggle我在Excel-VBA中非常基础,并且遇到了问题。

我的解决方案要求我在“ Y”和“ N”两列之间切换“是”或“否”。 在本练习中,单元格值为“是”或“否”的行将保持固定,直到手动编辑但不能同时具有“是”和“否”。 用简单的话来说,代码需要在每次单击时在指定行中的同一行中的是或否之间进行切换。

该图显示了我的第一个切换操作。不适合我的解决方案。

但是我的代码倾向于执行其他操作。我已经设法编译了。但是需要一些帮助。

Sub Toggle()
    Dim i As Integer
    For i = 1 To 10    ' Cell Range to lookup
        If Cells(i, 5).Value = "No" Then
            Cells(i, 4).Value = "Yes"
            Cells(i, 5).ClearContents ' Must clear No value before switching to Yes
        ElseIf Cells(i, 4).Value = "Yes" Then
            Cells(i, 5).Value = "No"
            Cells(i, 4).ClearContents 'Must clear Yes value before switching to No
        Exit Sub

        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox ("Value not found in the range!")
End Sub

1 个答案:

答案 0 :(得分:0)

我想通过一些故障排除,我能够从我的代码中简单删除“ Exit Sub”来达到结果,并且可以按照我想要的方式切换单元格中的值!