excel - 将字符串值传递给函数并返回集合对象 VBA

标签 excel vba

出于某种原因,以下代码不会将字符串传递给函数,但如果字符串变量硬编码到函数,则可以很好地返回集合。

我收到以下错误

Compile error: Argument not optional

指向findlastrow()中的

Set Dimensions = findlastrow()  --line 8

这是代码。

主子:

Sub SheetCopier()

Dim TargetlRow As Long
Dim TargetlCol As Long
Dim Tabname As String

Dim Dimensions As Collection
Set Dimensions = findlastrow()

TargetControlTab = "tab1"
Tabname = TargetControlTab


Call findlastrow(Tabname)

MsgBox "Last Row: " & Dimensions.Item(1) & vbNewLine & "Last Column: " & Dimensions.Item(2)

End Sub

功能:

   Function findlastrow(Tabname As String) As Collection
   'Finds the last non-blank cell in a single row or column

    Dim FilledDimensions As Collection
    Set FilledDimensions = New Collection


     Sheets(Tabname).Select
    'Find the last non-blank cell in column A(1)
    TargetlRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Find the last non-blank cell in row 1
    TargetlCol = Cells(1, Columns.Count).End(xlToLeft).Column

    FilledDimensions.Add TargetlRow
    FilledDimensions.Add TargetlCol

    Set findlastrow = FilledDimensions

    End Function

最佳答案

您已将 Tabname 定义为 findlastrow 函数的参数,并且您尝试在函数内再次定义它,但您不能这样做,因此

删除这一行:Tabname As String

并按如下说明修改子内容:

Sub SheetCopier()

    Dim TargetlRow As Long
    Dim TargetlCol As Long
    Dim Tabname As String

    Dim Dimensions As Collection
'this line is the problem since you are not passing a worksheet to the function
    'Set Dimensions = findlastrow()

 TargetControlTab = "tab1"
 Tabname = TargetControlTab


 set Dimensions=findlastrow(Tabname) 

 MsgBox "Last Row: " & Dimensions.Item(1) & vbNewLine & "Last Column: " & Dimensions.Item(2)
end sub

关于excel - 将字符串值传递给函数并返回集合对象 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971693/

相关文章:

excel - VBA Excel访问具有命名范围的索引

excel - 联盟没有选择所有范围

vba - 是否可以同时将 VBA MsgBox 作为 vbYesNo 和 vbExclamation 类型?

Excel VBA 在非默认日历中创建 session

excel - 根据另一个值和范围查找值

excel - 将 OOo 宏转换为 Excel 宏

excel - 如果 Excel VBA 代码执行过早结束,会触发什么事件?

excel - DAX日历动态假期功能

string - VBA - 使用 startPOS 和 endPOS 拆分字符串函数

Excel VBA - 如何找到字典中最小和最大的键