简体   繁体   English

固定:使用变量引用Excel工作表名称

[英]FIXED: Reference an Excel Sheet Name with a variable

==============FIXED========== ==============固定==========

I have a function: 我有一个功能:

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

When I try to use that function . 当我尝试使用该功能时。 . .

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

. . . I get a subscript out of Range (run-time error '9') error. 我收到下标超出范围(运行时错误'9')错误。 How can I make the error go away? 如何使错误消失?

running getLastRow = Worksheets("Data").Cells(Rows.count, 1).End(xlUp).row works fine. 运行getLastRow = Worksheets(“ Data”)。Cells(Rows.count,1).End(xlUp).row运行正常。 But I want to be able to dynamically choose the sheet name in my function. 但是我希望能够在我的函数中动态选择工作表名称。

Problem is because incorrect workbook is activated. 问题是因为激活了不正确的工作簿。

try this: 尝试这个:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM