我正在构建一个函数,当您选择一个单元格时,输出是从所选内容到同一列上最后一个填充的单元格行的单元格范围。
这是完美运行的代码。
''Get the cell range from selection to last cell
Function CellRange(CellA As Range)
CellRange = CellA.Address + ":" + CellA.End(xlDown).Address
End Function
问题: 我想更新此代码,以便在用于日期时,用户可以使用三个选项进行过滤:YTD(年初至今)、ALL(所有时间 - 即获取所有数据)、一年(即 2015/2014/2013 等) .)
我的最终目标是让用户在日期范围列中选择一个单元格并输入YTD或全部或给定年份(即2014) 并使用他的过滤器获取范围。
示例:用户写入 =cellrange(A2,2014)
,这应该产生 $A$2:$A$23
并且如果用户更改为 =cellrange(A2,2014)
这应该产生 $A$24:$A$40
如图像所示。
我尝试了各种循环或计数,但我感到很失落,因为我的尝试显然没有任何意义。
我正在寻找一些帮助:最好是问题的指导或解决方案,因为我想在解决这个问题后在此基础上进行构建(因此我在 VBA 上进行此操作)。
最佳答案
这是一个更短的解决方案,适用于所有三种场景,并且不需要数据工作表处于事件状态:
Public Function cellrange(rDates As Range, vFilter As Variant) As String
Dim i As Long, ndx1 As Long, ndx2 As Long, r As Range, vA As Variant, bErr As Boolean, bAll As Boolean
bErr = True
If IsDate(rDates) Then
With rDates.EntireColumn
i = rDates.Parent.Evaluate("count(" & .Address & ")")
Set r = .Cells(1 - i + rDates.Parent.Evaluate("index(" & .Address & ",match(9.9E+307," & .Address & "))").Row).Resize(i, 1)
End With
vA = r.Value
Select Case LCase(vFilter)
Case "all": bErr = 0: bAll = 1
Case "ytd"
For i = 1 To UBound(vA)
If ndx1 = 0 And Year(vA(i, 1)) = Year(Date) Then ndx1 = i
If vA(i, 1) <= Date Then ndx2 = i
Next
Case Else 'year
vFilter = Val(vFilter)
If vFilter Then
For i = 1 To UBound(vA)
If ndx1 = 0 And Year(vA(i, 1)) = vFilter Then ndx1 = i
If ndx1 And Year(vA(i, 1)) = vFilter Then ndx2 = i
Next
End If
End Select
If Not bAll Then If ndx1 > 0 And ndx2 > 0 Then Set r = r.Range(r.Parent.Cells(ndx1, 1), r.Parent.Cells(ndx2, 1)): bErr = False
If Not bErr Then cellrange = r.Address Else cellrange = CVErr(xlErrValue)
End If
End Function
关于vba - 如何使用 VBA 构建动态单元格范围输出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31568636/