出于某种原因,以下代码不会将字符串传递给函数,但如果字符串变量硬编码到函数,则可以很好地返回集合。
我收到以下错误
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/