我怎样才能使以下功能起作用?
Public Function DataRange(Somesheet as String, Optional StartCell as String) as Excel.Range
If StartCell = "" Then
DataRange =ThisWorkbook.Sheets( Somesheet).Range( ThisWorkbook.Sheets( Somesheet)_
.Cells(1,1).End(xldown),ThisWorkbook.Sheets(Somesheet).Cells(1,1).End(xlright))
Else
DataRange = ThisWorkbook.Sheets(Somesheet).Range(ThisWorkbook.Sheets(Somesheet)_
.Range(Startcell).End(xldown),ThisWorkbook.Sheets(Somesheet).Range(Startcell).End(xlright))
End If
End Function
答案 0 :(得分:1)
我假设你的If StartCell = ""
无效。将Startcell变量更改为变体,这将允许您使用ismissing
函数检查是否已通过,并指定您自己的默认值(如果它没有)。 IsMissing仅适用于变体数据类型。如果需要,在将参数传递给函数时使用Cvar()
答案 1 :(得分:1)
Public Function DataRange(Somesheet as String, _
Optional StartCell as String = "A1") as Excel.Range
With ThisWorkbook.Sheets(Somesheet)
Set DataRange = .Range(.Range(Startcell).End(xldown), _
.Range(Startcell).End(xltoright))
End With
End Function
注意:xlToRight
不是xlRight
用法:
Dim rng
Set rng = DataRange("Sheet1") 'uses default A1 as top-left cell
Set rng = DataRange("Sheet1", "E10") 'uses E10
这可能同样有效:
ThisWorkbook.Sheets(Somesheet).Range(Startcell).CurrentRegion