【问题标题】:how to store specific cells into an array? vba-excel如何将特定单元格存储到数组中? vba-excel
【发布时间】:2014-07-29 09:14:46
【问题描述】:

我有这个:
A栏
第 1 行:str1;str2;str3
第 2 行:str4;str5;str6
第 3 行:str7;str8;str9
.....................
行: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)并将它们分隔在不同的行中。

谁能帮帮我?也许有人有其他想法我该怎么做?

【问题讨论】:

  • 为什么不使用以“;”为标准的自动过滤器,然后循环遍历可见单元格?
  • 要不要像这样添加arr(0) = str1, arr(1) = str2, arr(3) = str3, arr(n) = strn?
  • 是的,@Jagadish Dabbiru
  • @Rory,我必须使用 VBA 代码..
  • 我的意思是使用 VBA 代码——我没想到你会用手来做。 :)

标签: arrays vba excel


【解决方案1】:

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

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 的数组,由分号字符之间的所有字符串组成

【讨论】:

  • 非常感谢!这就是我需要的。但是如果我需要分号之前或之后的字符串(我的意思是将字符串放入新行),我必须操作拆分行代码,对吗?
  • 对不起,我不明白你的意思?
【解决方案2】:

我指的是这样的东西:

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 方法的变体,将所有数据加载到数组中并进行处理 - 它应该比逐个单元格读取更快。

【讨论】:

  • 你的想法也很棒!但是,是的,Dave 的代码处理速度更快。还是谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多