在VBA中返回,没有达到我的预期

时间:2012-06-28 08:13:15

标签: excel vba excel-vba return

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

IDE说预期声明结束,我该怎么办? (返回id相同的行?)

我对VBA一点也不熟悉,但是当我从微软看这个例子时这应该有用吗? :

  

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

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

2 个答案:

答案 0 :(得分:6)

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

GetRowToWriteOn = row  

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

答案 1 :(得分:0)

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