vba - 如何使用 VBA 构建动态单元格范围输出函数

标签 vba excel

我正在构建一个函数,当您选择一个单元格时,输出是从所选内容到同一列上最后一个填充的单元格行的单元格范围。

这是完美运行的代码。

''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 如图像所示。

enter image description here

我尝试了各种循环或计数,但我感到很失落,因为我的尝试显然没有任何意义。

我正在寻找一些帮助:最好是问题的指导或解决方案,因为我想在解决这个问题后在此基础上进行构建(因此我在 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/

相关文章:

python - 使用 Python 填写 Excel 文件的简单方法

SQL CopyFromRecordSet 在 VBA 中无故变慢

excel - 考虑到过滤器,如何计算列的中位数?

python - 我不知道为什么我得到一个空白的输出文件

XML 模式 - 导入模式中的新行

json - curl URL 并在 Excel 单元格中发布结果?

excel - 将 Cell.Address 保存在数组中并将其用作单元格公式中的变量

excel - 从一个单元格创建一个弹出 InputBox 并将值右移到下一个

python - 如何获取 xlsx 文件的边框使用 xlrd/

VBA。比较锯齿状数组结果为 "Type Mismatch"