简体   繁体   English

Excel VBA - 将数据从单元格解析为数组

[英]Excel VBA - parse data from cell into array

I have data in one cell (E2) that consists of numbers separated by a comma and a space (ie 1, 14, 33, 46, 22, 3 ). 我在一个单元格(E2)中有数据,由逗号和空格分隔的数字组成(即1, 14, 33, 46, 22, 3 )。 There can be up to 1,000 numbers in the cell. 单元格中最多可以有1,000个数字。 I want to take these numbers and put them in an array so I can then match them to a variable I call AudienceNumber . 我想取这些数字并将它们放在一个数组中,然后我可以将它们与我称之为AudienceNumber的变量相匹配。 If the array contains the number 1 or the AudienceNumber I want to write the row that I built the array from (row 2 in this case) to a new workbook. 如果数组包含数字1AudienceNumber我想将我构建数组的行(在本例中为第2行)写入新工作簿。 If the array doesn't contain 1 or the AudienceNumber I want to go to cell E in the next row and repeat the process. 如果数组不包含1AudienceNumber我想转到下一行的单元格E并重复该过程。 I want to continue doing this until cell E is blank. 我想继续这样做,直到单元格E为空。 I can't seem to get the contents of cell E2 into the an array. 我似乎无法将单元格E2的内容放入数组中。 Here's what I got: 这是我得到的:

Dim AudienceArray (1000) as Variant
ActiveWorkbook.Worksheets("Data").Select
Range("E2").Select
AudienceArray=Sprlit(ActiveCell.Value,",")

When I run the sub I'm getting a 当我运行sub我得到了一个

Can't Assign to Array Error 无法分配给阵列错误

message. 信息。 I can't seem to figure out what I'm doing wrong. 我似乎无法弄清楚我做错了什么。 Any help would be appreciated. 任何帮助,将不胜感激。

Try this: 尝试这个:

Option Explicit

    Sub Test()

        Dim ws As Worksheet
        Dim val As String
        Dim arr As Variant
        Dim i As Long

        Set ws = ActiveWorkbook.Worksheets("Data")
        val = ws.Range("E2").Text
        arr = Split(val, ",", -1, vbBinaryCompare)

        For i = 0 To UBound(arr)
            Debug.Print arr(i)
            'split retains spaces...
            Debug.Print Trim$(arr(i))
        Next i

    End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM