修复:使用变量引用Excel工作表名称

时间:2014-07-15 14:35:17

标签: excel vba excel-vba

============== FIXED ==========

我有一个功能:

Public Function getLastRow(sheetName As String) As Integer
    getLastRow = Worksheets(sheetName).Cells(Rows.count, 1).End(xlUp).row
End Function

当我尝试使用该功能时。 。 。

Sub test()
MsgBox getLastRow("Data")
End Sub

。 。 。我得到一个超出范围(运行时错误' 9')错误的下标。如何让错误消失?

运行getLastRow =工作表("数据")。单元格(Rows.count,1).End(xlUp).row工作正常。但我希望能够在我的函数中动态选择工作表名称。

1 个答案:

答案 0 :(得分:0)

问题是因为激活了错误的工作簿。

试试这个:

Public Function getLastRow(sheetName As String) As Integer
    getLastRow = ThisWorkbook.Worksheets(sheetName).Cells(Rows.Count, 1).End(xlUp).Row
End Function

Public Function getLastRow(workbookName As String, sheetName As String) As Integer
    getLastRow = Workbooks(workbookName).Worksheets(sheetName).Cells(Rows.Count, 1).End(xlUp).Row
End Function