VBA从一个数组复制值并将它们存储到另一个数组

时间:2017-11-13 17:40:59

标签: arrays excel vba excel-vba

我希望能够找到当前VBA问题的帮助。我已经浏览了Stack Overflow和其他Google搜索,但似乎无法找到我正在寻找的内容。

基本上,我在页面上有一个用户粘贴的值,我在逗号上分隔,然后将其存储到数组中。我的目标是循环遍历该数组并消除任何额外的空格,然后删除任何不是数字的值。

  1. 复制用户值
  2. 存储到数组
  3. 删除空白
  4. 到目前为止,我还没能:

    1. 将数字项目复制到新数组
    2. 目前,我的代码如下:

      Sub grabText()
      
      ' This macro was written as a test macro to grab and filter data entered in a textbox
      
          Application.ScreenUpdating = False
      
          Dim enteredValue As String ' Value taken from page
          Dim vals() As String ' Array once it is split
          Dim goodvals() As String 'Formatted array
          Dim i As Integer 'Index
      
          enteredValue = ActiveSheet.myTxt.Text
         ' MsgBox enteredValue
      
          vals() = Split(enteredValue, ",")
      
          lastitem = UBound(vals)
         ' MsgBox lastitem
      
          'Formats array
          For i = LBound(vals) To UBound(vals)
              i = TRIM(vals(i))
              '
              '   If (ISNUMBER(vals(i)) == TRUE) Then
              '       enter i into goodvals()
              '
          Next i
      
          Application.ScreenUpdating = True
      

      非常感谢任何帮助或建议。我正在考虑用其他语言(Java,Python)做到这一点的方法,我正在考虑链接列表。

      提前致谢!

1 个答案:

答案 0 :(得分:3)

一些问题:

  • 不要将Split的结果分配给vals(),而是vals
  • 不要将变量i重新用于Trim的结果。最好为其使用单独的变量,然后可以键入String

如果

,您可以捕获所需的结果
  • 首先为目标数组保留足够的空间:它永远不会超过Split结果,因此请将其用作初始大小
  • 使用单独的索引变量来引用目标数组索引,只有在其中存储了数字时才增加它
  • 最后将目标数组的大小减小到实际使用的大小

代码:

Dim enteredValue As String ' Value taken from page
Dim vals() As String ' Array once it is split
Dim goodvals() As String  'Formatted array
Dim i As Long 'Index in vals
Dim j As Long 'Index in goodvals
Dim s As String 'Individual string

enteredValue = ActiveSheet.myTxt.Text

vals = Split(enteredValue, ",")
' Reserve as many entries in the target array
ReDim goodvals(UBound(vals))

j = LBound(goodvals)
For i = LBound(vals) To UBound(vals)
    s = Trim(vals(i))
    If IsNumeric(s) Then 
        goodvals(j) = CDbl(s)
        MsgBox goodvals(j)
        j = j + 1
    End If
Next

' Shorten the array size to the part that is used
If j Then
    ReDim Preserve goodvals(j - 1)
Else ' There were no numericals at all, so erase the array:
    Erase goodvals
End If