VBA从一个数组中复制值并将其存储到另一个数组中

我希望能find当前VBA问题的帮助。 我已经看遍整个堆栈溢出和其他谷歌search,但似乎无法find我在找什么。

本质上,我有一个用户在我的页面粘贴值,我用逗号分隔,然后将其存储到一个数组。 我打算做的是然后循环通过该数组,并消除任何额外的空间,然后还删除任何值不是一个数字。

  1. 复制用户值
  2. 存储到一个数组中
  3. 擦除空白

到目前为止,我还没有能够:

  1. 将数字项目复制到新arrays

目前,我的代码如下所示:

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 

任何帮助或build议将不胜感激。 我正在考虑以其他语言(Java,Python)来做这件事的方法,我正在考虑链接列表。

提前致谢!

一些问题:

  • 不要将Split的结果赋值给vals() ,而是赋值给vals
  • 不要重复使用variablesi作为Trim结果。 最好使用一个单独的variables,然后您可以键入一个String

如果你能捕获所需的结果

  • 首先为您的目标arrays预留足够的空间:它永远不会比Split结果长,所以使用它作为初始大小
  • 使用单独的索引variables来引用目标数组索引,并且只有在存储数字时才增加索引
  • 最后将目标数组的大小减小到实际使用的大小

码:

 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