2016-02-25 127 views
0

我試圖刪除矢量中的行,這取決於將返回向量的VBA函數中的另一個向量的值。謝謝。刪除向量中的行VBA Excel

例如:

條件= [1; 0; 1; 1; 0](5x1)

Data = [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 
+0

你從工作表單元格運行此作爲UDF,或者從另一個VBA程序? UDF不能刪除工作表上的單元格。另外,你聲明nRowData和nRowCond,但是不要設置它們中的任何一個的值... –

+0

對不起。我忘記了包含矢量大小的代碼(nRowData和nRowCond)。現在糾正了。 – Ali

+0

至於功能,是的,我從工作表中運行這個。我想使用兩個矢量來創建一個新的矢量RANGEIF。然後我將在一個函數中使用RANGEIF。 例如:AVERAGE(RANGEIF(A1:A5,B1:B5)) 謝謝蒂姆。 – Ali

回答

0

這將工作只要不是所有值都被過濾掉了......

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 
+0

非常感謝蒂姆。 – Ali