嵌套If语句未选择适当的单元格值

时间:2017-03-06 02:01:09

标签: excel vba excel-vba if-statement

我在表单上有3个组合框。第一个是在表单加载时填充的,第二个是在用户从第一个组合框中选择一个值时填充的,第三个是在用户从第二个组合框中选择一个值时填充的。

当更改第三个组合框时,我使用嵌套的If语句来确定此组合所在的行(因此我可以在表单上填充文本框)。但是,第一个If语句未能触发(即返回' true'值)。单元格中有一个可接受的值,因此它应该进入下一个If语句,但它只是跳到我的While语句的末尾。

Private Sub cmb_State_Change()
    Dim Project, licence, state As String
    Dim selectedrow As Integer

    Dim LastRow As Integer
    Dim i, j As Integer

    selededrow = 0
    Project = cmb_Project.Value
    licence = cmb_Licence.Value
    state = cmb_State.Value

    i = 1
    j = 3
    While selectedrow = 0
        If Worksheets("Entitlements").Cells(i, j) = Project Then
            i = i + 6
            If Worksheets("Entitlements").Cells(i, j) = licence Then
                i = i - 1
                If Worksheets("Entitlements").Cells(i, j) = state Then
                    selectedrow = j
                End If
            End If
        Else
            j = j + 1
            i = i - 5
        End If
    Wend

End Sub

有人能看出为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

Cells将其参数视为行然后列,因此您需要在代码中反转ij。当您执行Range("C4")时,它是列,然后是行,即列C,行4 - 但Cells是另一种方式。

所以,目前你有

If Worksheets("Entitlements").Cells(i, j) = Project Then
i = i + 6
    If Worksheets("Entitlements").Cells(i, j) = licence Then
        i = i - 1
        If Worksheets("Entitlements").Cells(i, j) = state Then
                selectedrow = j

这使你的第二次查找减少了6行 - 而不是6列。

将其重写为:

If Worksheets("Entitlements").Cells(j, i) = Project Then
i = i + 6
    If Worksheets("Entitlements").Cells(j, i) = licence Then
        i = i - 1
        If Worksheets("Entitlements").Cells(j, i) = state Then
                selectedrow = j

另一个选项

您可以像这样重写代码块:

r = 3
While selectedrow = 0
    If Worksheets("Entitlements").Cells(r, 1) = Project And _
        Worksheets("Entitlements").Cells(r, 7) = licence And _
        Worksheets("Entitlements").Cells(r, 6) = State Then

        selectedrow = r
    Else
        r = r + 1
    End If
Wend

更好的选择

使用While..Wend循环意味着如果没有匹配,代码将运行到工作表中的最后一行(超过百万行)。您可以使用标准位代码查找数据的最后一行:

Set ws = Worksheets("Entitlements")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

然后在该范围内使用For..Next循环。例如:

Option Explicit

Private Sub cmb_State_Change()
    Dim Project As String, licence As String, state As String
    Dim selectedrow As Integer
    Dim LastRow As Integer
    Dim r As Integer
    Dim ws As Worksheet

    selectedrow = 0
    Project = "hello" 'cmb_Project.Value
    licence = "world" 'cmb_Licence.Value
    state = "stuff" 'cmb_State.Value

    Set ws = Worksheets("Entitlements")
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For r = 3 To LastRow
        If ws.Cells(r, 1) = Project And _
            ws.Cells(r, 7) = licence And _
            ws.Cells(r, 6) = state Then

            selectedrow = r
            Exit For
    Next r

End Sub

请注意使用Option Explicit来捕获代码中的任何拼写错误。在您的原始问题中,您有Dim selectedrow As Integerselededrow = 0如果使用“Option Explicit”,则会抛出编译时错误。