【问题标题】:Delete Row out of multi-dim array从多维度数组中删除行
【发布时间】:2020-02-27 10:43:37
【问题描述】:

我有以下代码,现在卡住了。 而不是这一行,我实际上想删除该行。该怎么做?

cData(rw, 5) = "Matching DES found"

For rw = 1 To UBound(cData, 1)
            'For Each e In cRng
            For rw2 = 1 To UBound(cData, 1)
                If Left(cData(rw, 1), 4) <> "DES_" Then
                    a = cData(rw, 3)

                    If Left(cData(rw2, 1), 4) = ("DES_") And Right(cData(rw2, 1), Len(a)) = a Then
                        cData(rw, 5) = "Matching DES found"


                        'cData(rw, 1) = Empty
                        Exit For
                        'GoTo nextI
                        Exit For
                   Else
                       cData(rw, 5) = "unique"
                       'GoTo nextE
                   End If
               Else
                   'GoTo nextI
                   Exit For
               End If
'nextE:
           Next
'nextI:
       Next

【问题讨论】:

  • 如果您要删除行,您需要在循环中后退一步,否则可能会无意间跳过行。
  • 您是否有很大的范围可以检查特定条件?如果是,您可以使用新范围,将要删除的特定单元格合并,最后一次删除该范围的所有行。否则,您可以像 braX 已经建议的那样继续。
  • @brax 好的,所以每当执行 if 条件时,我都会重置 rw=rw-1。但首先...我如何删除行?
  • 这能回答你的问题吗? Delete a row in Excel VBA

标签: excel vba


【解决方案1】:

这是在内存中使用 ListBox 的解决方案: (向后删除)

Set ListBoxData = CreateObject("New:{8BD21D20-EC42-11CE-9E0D-00AA006002F3}") 'Listbox
ListBoxData.List = cData
For rw = ListBoxData.ListCount - 1 To 0 Step -1
            'For Each e In cRng
            For rw2 = ListBoxData.ListCount - 1 To 0 Step -1
                    If Left(ListBoxData.List(rw, 0), 4) <> "DES_" Then
                    a = ListBoxData.List(rw, 2)

                    If Left(ListBoxData.List(rw2, 0), 4) = "DES_" And Right(ListBoxData.List(rw2, 0), Len(a)) = a Then
                        ListBoxData.List(rw, 4) = "Matching DES found"
                ListBoxData.RemoveItem rw 'remove your row

                        'ListBoxData(rw, 1) = Empty
                        Exit For
                        'GoTo nextI
                        'Exit For
                   Else
                       ListBoxData.List(rw, 4) = "unique"
                       'GoTo nextE
                   End If
               Else
                   'GoTo nextI
                   Exit For
               End If
'nextE:
           Next
'nextI:
       Next
       newcData = ListBoxData.List 'cleaned Listboxdata to a new Array, but lbound = 0 so act accordingly

【讨论】:

  • 我将 listboxdata 声明为什么?
  • 作为对象(或者当您的工作表中有用户表单时,您可以使用 MSForms.ListBox)
  • 无法设置列表属性。无效的属性数组索引 --> 错误。在 ListboxData.List = cData
  • 您必须像以前的代码一样使用 cData,或者将工作表中的数据直接设置为 ListBoxList。我的答案是替换您在 OP 中发布的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2023-03-31
  • 2014-11-17
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
相关资源
最近更新 更多