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

时间:2018-08-22 16:53:03

标签: excel vba

由于某些原因,以下代码没有将字符串传递给函数,但是如果将字符串变量硬编码到函数中,则返回的集合会很好。

我收到以下错误

  

编译错误:参数不可选

指向中的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

1 个答案:

答案 0 :(得分:4)

您已经将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