删除数组中的元素,如果元素有一定的价值VBA [英] Deleting Elements in an Array if Element is a Certain value VBA

查看:326
本文介绍了删除数组中的元素,如果元素有一定的价值VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局数组, prLst()变长的,可以。这需要在数量上为字符串1 UBOUND(prLst)。但是,当用户输入0,我想从列表中删除该元素。我有以下的code编写执行此:

I have a global array, prLst() that can of variable length. It takes in numbers as strings "1" to Ubound(prLst). However, when the user enters "0", I want to delete that element from the list. I have the following code written to perform this:

count2 = 0
eachHdr = 1
totHead = UBound(prLst)

Do
    If prLst(eachHdr) = "0" Then
        prLst(eachHdr).Delete
        count2 = count2 + 1
    End If
    keepTrack = totHead - count2
    'MsgBox "prLst = " & prLst(eachHdr)
    eachHdr = eachHdr + 1
Loop Until eachHdr > keepTrack

这是行不通的。怎样有效地在数组中删除元素 prLst 如果元素是0

This does not work. How do I efficiently delete elements in the array prLst if the element is "0"?

注意:这是一个更大的计划,对此的描述可以在这里找到的一部分:<一href=\"http://stackoverflow.com/questions/6671273/excel-vba-macro-sorting-with-groups-or-linked-rows\">Sorting行组Excel的VBA宏

NOTE: This is part of a larger program, for which the description of can be found here: Sorting Groups of Rows Excel VBA Macro

推荐答案

数组是具有一定规模的结构。您可以使用VBA动态数组,可以缩小或使用使用ReDim增长,但不能删除中间的元素。这不是从你的样品清楚如何阵列功能的工作原理,或如何确定索引位置(eachHdr),但你基本上有3种选择

An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options

(A)编写自定义删除功能,为您的阵列状(未经测试)

(A) Write a custom 'delete' function for your array like (untested)

Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(prLst)
            prLst(i - 1) = prLst(i)
        Next

        ' Shrink the array by one, removing the last one
        ReDim Preserve prLst(Len(prLst) - 1)
End Sub

(B)只需设置一个虚拟值作为值而不是实际删除元素

(B) Simply set a 'dummy' value as the value instead of actually deleting the element

If prLst(eachHdr) = "0" Then        
   prLst(eachHdr) = "n/a"
End If

(三)停止使用数组并将其转换为一个VBA.Collection。集合是一个(唯一的)键/值对结构,其中您可以自由添加或删除

(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from

Dim prLst As New Collection

这篇关于删除数组中的元素,如果元素有一定的价值VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆