如何将特定单元格存储到数组中? VBA-Excel中

时间:2014-07-29 09:14:46

标签: arrays vba excel-vba excel

我有这个:
        栏A
        row1:str1; str2; str3
        row2:str4; str5; str6
        row3:str7; str8; str9
        ....................
        rown:strn; strn; strn

以下代码找到";"字符A列:

     Range("A:A").Find(What:=";", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
     xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=False).Activate

我想将所有行(从列A,包含分号字符)放入数组中。我尝试使用SET,如下所示:

       dim r as Variant
       Set r = Range("A:A").Find(What:=rngsearch, After:=ActiveCell, LookIn:=xlFormulas, LookAt:=_  
       xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext,MatchCase:=False _
       , SearchFormat:=False).Activate

......但不起作用。它的运行时错误' 13',输入不匹配

我需要这个数组(包含所有带分号的单元格)因为我想提取字符串(从str1到strn)并将它们分成不同的行。

任何人都可以帮助我吗?也许有人知道我该怎么做?

2 个答案:

答案 0 :(得分:0)

可能有更有效的方法可以做到这一点,我个人更愿意避免引用整个专栏,但这应该有希望做到你期望的那样:

Sub test()

Dim ws As Worksheet
Dim rng As Range
Dim cel As Range
Dim strTmp As String
Dim arrFinal As Variant

Set ws = Sheets("Sheet1")
Set rng = ws.Range("A:A")

' Loop through all cells in column A
For Each cel In rng.Cells
    ' Is there a semicolon character in the cell?
    If InStr(1, cel.Value, ";") > 0 Then
        ' Add the cell value to strTmp and add a _
            semicolon at the end to separate this _
            row from the next row
        strTmp = strTmp & cel.Value & ";"
    End If
Next cel

' Split strTmp into an array
arrFinal = Split(strTmp, ";")

End Sub

最终结果是一个名为arrFinal的数组,分号为

之间的所有字符串

答案 1 :(得分:0)

我指的是这样的事情:

Sub GetSemicolonData()
    Dim rngCell               As Excel.Range
    Dim asValues()            As String
    Dim lngCount              As Long
    Dim x                     As Long


    With Range("A1").CurrentRegion.Columns(1)
        .AutoFilter field:=1, Criteria1:="*;*"
        lngCount = .SpecialCells(xlCellTypeVisible).Count
        If lngCount > 1 Then
            x = 1
            ' exclude header row
            ReDim asValues(1 To lngCount - 1)
            For Each rngCell In .SpecialCells(xlCellTypeVisible)
                If rngCell.Row > 1 Then
                    ' load value into array
                    asValues(x) = rngCell.Value
                    x = x + 1
                End If
            Next rngCell
        End If
    End With
End Sub

您还可以使用Dave方法的变体将所有数据加载到数组中并进行处理 - 它应该比逐个单元格读取更快。