vba VB - 附加到数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5472144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:54:46  来源:igfitidea点击:

VB - Append to array?

arraysvbavbscript

提问by Kenny Bones

this is probably a super simple question. But I have this Array that I need to strip useless parts from. But I still want it in an array.

这可能是一个超级简单的问题。但是我有这个数组,我需要从中去除无用的部分。但我仍然希望它在一个数组中。

So, the array looks like this when it comes in:

所以,当它进来时,数组看起来像这样:

ArrValues(0) "Firstname=FIRSTNAME"
ArrValues(1) "Lastname=LASTNAME"
ArrValues(2) "Username=USERNAME"
ArrValues(3) "Displayname=DISPLAYNAME"

Then I send this array through this code snippet:

然后我通过这个代码片段发送这个数组:

For Each s In arrValues
    s = Split(s, "=")
    s = s(1)
Next

This strips the strings so I get only FIRSTNAMEand so on. But, I want to send each cleaned string into an array again. How do I do that?

这会剥离字符串,所以我只能得到FIRSTNAME等等。但是,我想再次将每个清理过的字符串发送到一个数组中。我怎么做?

采纳答案by Tiago Cardoso

As long as you have all strings with an '=' sign, this code should work... using MID function. I'm not an performance expert, but I believe that a MID function would have a better performance than the SPLIT (since split will redim each value).

只要您的所有字符串都带有 '=' 符号,此代码应该可以工作...使用 MID 函数。我不是性能专家,但我相信 MID 函数会比 SPLIT 具有更好的性能(因为 split 会重新调整每个值)。

Still, Helen's code might work as well. Just sharing this code to show my MID approach :)

尽管如此,海伦的代码也可能有效。只是分享这个代码来展示我的 MID 方法:)

Sub MidArray()

    Dim ArrValues(3) As Variant
    Dim vValue As Variant
    Dim iCount As Integer

    ArrValues(0) = "Firstname=FIRSTNAME"
    ArrValues(1) = "Lastname=LASTNAME"
    ArrValues(2) = "Username=USERNAME"
    ArrValues(3) = "Displayname=DISPLAYNAME"

    For iCount = LBound(ArrValues) To UBound(ArrValues)

        ArrValues(iCount) = Mid(ArrValues(iCount), InStr(ArrValues(iCount), "=") + 1)

    Next iCount

End Sub

回答by Helen

To write back to the array, you need to use the ArrValues(index) = new_valuenotation. So, you need to use a regular Forloop instead of For Each, and access the array elements by their indexes. Here's how you can do this:

要写回数组,您需要使用ArrValues(index) = new_value符号。因此,您需要使用常规For循环而不是For Each, 并通过索引访问数组元素。以下是您可以这样做的方法:

For i = LBound(ArrValues) To UBound(ArrValues)
 s = ArrValues(i)
 s = Split(s, "=")
 ArrValues(i) = s(1)
Next