【问题标题】:Delete rows in vector VBA Excel删除矢量 VBA Excel 中的行
【发布时间】:2016-06-08 22:09:22
【问题描述】:

我正在尝试删除向量中的行,具体取决于将返回向量的 VBA 函数中另一个向量的值。谢谢。

例如:

条件 = [1; 0; 1个; 1个; 0] (5x1)

数据 = [0.6; 0.7; 0.75; 0.81; 0.94] (5x1)

预期结果 = [0.6; 0.75; 0.81] (3x1)

Function RANGEIF(data As Range, condition As Range) As Range
'
' Inputs
'
' data:         Vector Nx1 of data
' condition:    Vector Nx1 of binairy conditions
'
' Outputs
'
' RANGEIF:      Vector Nx1 of specific data

' Variable declaration
Dim nRowData As Integer
Dim nRowCond As Integer

' Input vector size
nRowData = data.Rows.Count
nRowCond = condition.Rows.Count

' Input validation
If nRowData <> nRowCond Then
    msg = "Error: Input vector sizes do not match"
    MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
    GoTo endnow
End If

' Conditional range
For j = nRowCond To 1 Step -1
    If condition(j, 1).Value <> 1 Then
        data.Cells(j, 1).Delete
    End If
Next j

Set RANGEIF = data

endnow:

End Function

【问题讨论】:

  • 您是从工作表单元格作为 UDF 运行它,还是从另一个 VBA 过程运行它? UDF 不能删除工作表上的单元格。此外,您声明了 nRowData 和 nRowCond,但随后不设置其中任何一个的值...
  • 对不起。我忘记包含向量大小的代码(nRowData 和 nRowCond)。现在已更正。
  • 至于功能,是的,我正在从工作表中运行它。我想使用这两个向量来创建一个新向量RANGEIF。然后我将在函数中使用 RANGEIF。例如: AVERAGE ( RANGEIF ( A1:A5 , B1:B5 ) ) 谢谢 Tim。

标签: excel vba function conditional delete-row


【解决方案1】:

只要不是所有值都被过滤掉,这将起作用...

Function RANGEIF(data As Range, condition As Range)
    Dim n As Long, rv() As Variant, i As Long, msg, j As Long

    ' Input validation
    If data.Rows.Count <> condition.Rows.Count Then
        msg = "Error: Input vector sizes do not match"
        MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
        Exit Function
    End If

    n = Application.CountIf(condition, 1)
    If n > 1 Then
        ReDim rv(1 To n, 1 To 1)
        i = 1
        For j = 1 To data.Rows.Count
            If condition(j, 1).Value = 1 Then
                rv(i, 1) = data(j, 1)
                i = i + 1
            End If
        Next j
        RANGEIF = rv
    Else
        'what to do if no values are available?
        RANGEIF = "No values"
    End If

End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 2012-03-11
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多