在vba中删除String的匹配项

时间:2014-01-25 18:04:58

标签: excel-vba vba excel

我是vba编程的新手,目前正在开展以下工作:

  1. 记录数据的属性名称并将其记录到AttributeName()
  2. 请求用户选择目标/因变量
  3. AttributeName()
  4. 删除目标属性

    我有问题要继续执行第3步(我使用了Filter().Delete

    Dim DataRange As Range
    Dim nrow As Long
    Dim ncol As Long
    
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    
    Set DataRange = Selection
    nrow = DataRange.Rows.Count
    ncol = DataRange.Columns.Count
    
    Dim AttributeName() As String
    For i = 1 to ncol
            ReDim Preserve AttributeName(i)
        AttributeName(i) = Sheets("data").Cells(1,i).Value
    Next i
    
    
    Dim TargetRange as Range
        Dim Target as String
    Set TargetRange = Application.InputBox("Please highlight the cell for TARGET", Type:=8)
    Target = TargetRange.Value
    

    我的想法是:
     If AttributeName(i) = Target Then ...

    感谢您的温和帮助。

1 个答案:

答案 0 :(得分:0)

如果您要从AttributeName删除元素,请考虑使用集合link 1link 2)代替阵列:

Dim AttributeName As New Collection
For i = 1 To ncol
    AttributeName.Add Sheets("data").Cells(1, i).Value
Next i

Dim TargetRange As Range
Dim Target As String
Set TargetRange = Application.InputBox("Please highlight the cell for TARGET", Type:=8)
Target = TargetRange.Value

With AttributeName
    For i = .Count To 1 Step -1
        If .Item(i) = Target Then .Remove (i)
    Next
End With

还有一件重要的事情,如果用户在InputBox中按“取消”会怎么样?你也应该处理这个问题。

更改

Set TargetRange = Application.InputBox("Please highlight the cell for TARGET", Type:=8)

On Error Resume Next
Set TargetRange = Application.InputBox("Please highlight the cell for TARGET", Type:=8)
On Error Goto 0

If TargetRange Is Nothing Then
   MsgBox "User has pressed cancel"
   Exit Sub
End If