VBA宏功能超出范围

时间:2019-01-30 07:29:17

标签: excel vba

Function getNames()
    Dim  wbThis As Workbook,  arr() As Variant, i As Long
    Set wbThis = ThisWorkbook
    For i = 1 To 50
        arr(i) = wbThis.Sheets("Sheet1").Cells(6, i).Value
    Next i

    For i = 1 To 50
        MsgBox "employee names are***** ." + arr(i)
    Next i
End Function

我在Sheet1上有我的VBA宏代码。在sheet1中,我有一个单击按钮。单击按钮后,称为getNames函数。在sheet1中,我具有所有行和列值。但是当我运行它时,它会显示

  

下标超出范围/运行时错误'9'

我尝试了很多。对此没有任何想法。

1 个答案:

答案 0 :(得分:0)

您需要为变量数组分配一些大小。

Function getNames()
    Dim wbThis As Workbook, i As Long

    Set wbThis = ThisWorkbook

    redim arr(1 to 50) As Variant

    For i = lbound(arr) To ubound(arr)
        arr(i) = wbThis.Sheets("Sheet1").Cells(6, i).Value
    Next i

    For i = lbound(arr) To ubound(arr)
        MsgBox "employee names are***** ." & arr(i)
    Next i
End Function

ReDim可以不先使用Dim而使用。 LBoundUBound是一种从下边界到上边界循环遍历静态数组的更加通用的方法。与符号&是字符串连接的首选运算符。

函数旨在返回一个值。作为sub过程,可能会更好。

您可以通过从子程序中调用函数来“播种”数组。

sub main()

    dim i as long, nms as variant

    nms = getNames()

    For i = lbound(nms) To ubound(nms)
        MsgBox "employee names are***** ." & nms(i)
    Next i

end sub

Function getNames()
    Dim  wbThis As Workbook,  i As Long

    Set wbThis = ThisWorkbook

    redim arr(1 to 50) As Variant

    For i = lbound(arr) To ubound(arr)
        arr(i) = wbThis.Sheets("Sheet1").Cells(6, i).Value
    Next i

    getnames = arr

End Function