我希望能够找到当前VBA问题的帮助。我已经浏览了Stack Overflow和其他Google搜索,但似乎无法找到我正在寻找的内容。
基本上,我在页面上有一个用户粘贴的值,我在逗号上分隔,然后将其存储到数组中。我的目标是循环遍历该数组并消除任何额外的空格,然后删除任何不是数字的值。
到目前为止,我还没能:
目前,我的代码如下:
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)做到这一点的方法,我正在考虑链接列表。
提前致谢!
答案 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