VBA-无法从For循环的If语句中返回值

VBA-无法从For循环的If语句中返回值,vba,excel,if-statement,for-loop,return,Vba,Excel,If Statement,For Loop,Return,我有一个名为“checkConvert”的方法,它应该返回一个字符串 我创建了一个For循环,它在循环结束时返回一个值作为checkConvert。另外,在For循环中,我设置了一个Case,在这个Case中,另一个For循环中包含If语句。在这些If语句中,我还尝试返回一个值作为checkConvert,但是它根本不起作用 For i = val To lastColumn_source For j = 1 To 3 Dim cellValue As String

我有一个名为“checkConvert”的方法,它应该返回一个字符串

我创建了一个For循环,它在循环结束时返回一个值作为checkConvert。另外,在For循环中,我设置了一个Case,在这个Case中,另一个For循环中包含If语句。在这些If语句中,我还尝试返回一个值作为checkConvert,但是它根本不起作用

For i = val To lastColumn_source
    For j = 1 To 3
        Dim cellValue As String
        cellValue = salesSource.Cells(j, i).Value

        Select Case i
            Case 1
                Dim match As Boolean
                match = False                'Default is false.  
                                             'Equating two cells = false.

                For x = 1 To lastRow_check
                    If cellValue = sourceCheck.Cells(x, 1) Then
                        CRMDest.Cells(j, 2) = newName
                        match = True         'Match is found.  Thus, true.
                    End If
                    If x = lastRow_check And match = False Then
                        checkConvert = newName           'Supposed to return
                                                         'value.  Doesn't
                                                         'work.
                        MsgBox checkConvert              'But MsgBox works.
                    End If
                 Next x
            Case 2                                'Several more cases follow.
            Case 13
                 checkConvert = "End of Program."        'Returns String
                                                         'to "end program."
                                                         'This one works.
        End Select

        checkConvert = "Move."                           'This return also
                                                         'works.
    Next j
Next i
看起来您的印象是分配函数的返回值会立即返回。VBA不是这样工作的

您已经指定了一个返回值,但代码仍在运行,因为赋值就是:赋值

如果要在设置其返回值后立即退出函数,则需要显式退出:

    checkConvert = newName
    Exit Function

“起作用”的返回值仅仅是出于运气。您在循环中分配返回值,并且从不跳出循环,因此函数返回的值是上次迭代中分配给
checkConvert
的值。

My God。该死这很有道理。我会看看如果我执行“退出功能”会发生什么。非常感谢,Mat的杯子。(非常感谢。)
    checkConvert = newName
    Exit Function