Return in VBA, does not do what I expect

我只是一个虾纸丫 提交于 2020-01-03 02:29:10

问题


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?)

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

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

回答1:


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

GetRowToWriteOn = row  

The function name acts as a variable on its own.




回答2:


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


来源:https://stackoverflow.com/questions/11240563/return-in-vba-does-not-do-what-i-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!