在 VBA 中返回,不符合我的预期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11240563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:39:57  来源:igfitidea点击:

Return in VBA, does not do what I expect

excelvbaexcel-vbareturn

提问by Viktor Mellgren

Public Function GetRowToWriteOn(ByVal SheetName As String, ByVal id As Integer) As Integer
    LastRow = ActiveSheet.UsedRange.Rows.Count
    myarray = Sheets(SheetName).Range("d7:d" & LastRow).Value
    For row = 1 To UBound(myarray, 1)
        If (myarray(row, 1) = id) Then
            Return row
        End If
    Next
End Function

The IDE says expected end of statement, how do I do what I want? (Return the row where id is the same?)

IDE 说预期的语句结束,我该如何做我想做的事?(返回 id 相同的行?)

I'm not familiar at all with VBA, but when I look this example from microsoft this should work? :

我对 VBA 一点都不熟悉,但是当我从 microsoft 看这个例子时,这应该可行吗?:

The Return statement simultaneously assigns the return value and exits the function. The following example shows this.

Function myFunction(ByVal j As Integer) As Double
   Return 3.87 * j
End Function

Return 语句同时分配返回值并退出函数。以下示例显示了这一点。

Function myFunction(ByVal j As Integer) As Double
   Return 3.87 * j
End Function

回答by Trace

In VBA, returning a value is not done through the return keyword as it is custom in other languages. Try:

在 VBA 中,返回值不是通过 return 关键字完成的,因为它在其他语言中是自定义的。尝试:

GetRowToWriteOn = row  

The function name acts as a variable on its own.

函数名本身就是一个变量。

回答by Viktor Mellgren

Public Function GetRowToWriteOn(ByVal SheetName As String, ByVal idnr As Integer) As Integer
    LastRow = ActiveSheet.UsedRange.Rows.Count
    myarray = Sheets(SheetName).Range("d7:d" & LastRow).Value
    For row = 1 To UBound(myarray, 1)
        If (myarray(row, 1) = idnr) Then
            GetRowToWriteOn = row
            Exit Function
        End If
    Next
    GetRowToWriteOn = UBound(myarray, 1) + 1
    Exit Function 'Probably not needed :)
End Function