我有一个名为" 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
答案 0 :(得分:1)
checkConvert = newName 'Supposed to return 'value. Doesn't 'work. MsgBox checkConvert 'But MsgBox works.
看起来你的印象是分配函数的返回值会立即返回。这不是VBA的工作原理。
您已经分配了一个返回值,但代码仍在运行,因为,分配只是:赋值。
如果要在设置其返回值后立即退出该函数,则需要明确地执行此操作:
checkConvert = newName
Exit Function
“工作”的返回值,仅仅是出于好运。你在循环中分配返回值,并且永远不会跳出它,因此函数返回的值是最后一次迭代中最后一次赋值的值checkConvert
。