【问题标题】:Loop through column, store values in an array遍历列,将值存储在数组中
【发布时间】:2019-09-12 22:12:56
【问题描述】:

我正在尝试找到一种方法:

  1. 循环遍历一列(B 列)
  2. 取值,将它们存储在数组中
  3. 遍历该数组并进行一些文本操作

但是,我想不出一种方法来遍历一列并获取这些值,并将它们存储在一个数组中。我查看了 Stack Overflow 和 google,但没有找到成功的解决方案。

提前感谢您的帮助。

Sub collectNums()

Dim eNumStorage() As String ' initial storage array to take values
Dim i as Integer
Dim j as Integer
Dim lrow As Integer

lrow = Cells(Rows.Count, "B").End(xlUp).Row ' The amount of stuff in the column

For i = lrow To 2 Step -1
    If (Not IsEmpty(Cells(i, 2).Value)) Then ' checks to make sure the value isn't empty
    i = eNumStorage ' I know this isn't right
Next i

If (IsEmpty(eNumStorage)) Then
    MsgBox ("You did not enter an employee number for which to query our database. Quitting")
    Exit Sub
End If

End Sub

【问题讨论】:

  • 您特别纠结的是什么 - 网上有很多关于从范围创建数组的内容?
  • 我尝试了几种不同的方法,但是使用输入的 10 个员工编号的测试数据样本,我还没有找到一种方法将其存储到数组中。 @SJR

标签: excel vba


【解决方案1】:

这是将列转换为数组的最简单方法:

Public Sub TestMe()

    Dim myArray     As Variant
    Dim cnt         As Long

    myArray = Application.Transpose(Range("B1:B10"))

    For cnt = LBound(myArray) To UBound(myArray)
        myArray(cnt) = myArray(cnt) & "something"
    Next cnt
    For cnt = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(cnt)
    Next cnt
End Sub

它在数组中获取从B1B10 的值,并且可以将“某物”添加到该数组中。

Transpose() 函数采用单列范围并将其存储为一维数组。如果数组在单行上,那么您将需要双转置,以使其成为一维数组:

With Application
    myArray = .Transpose(.Transpose(Range("A1:K1")))
End With

【讨论】:

  • 你能解释一下 Transpose 函数在这里做什么吗?是否默认将每个单元格存储为数组中的值?
  • 感谢您的解释。我在您发布后不久就看到了 MSDN 文章。这很有帮助。
【解决方案2】:

只需在 Vityata 上添加一个变体,这是最简单的方法。此方法只会将非空白值添加到您的数组中。使用您的方法时,您必须使用 Redim 声明数组的大小。

Sub collectNums()

Dim eNumStorage() As String ' initial storage array to take values
Dim i As Long
Dim j As Long
Dim lrow As Long

lrow = Cells(Rows.Count, "B").End(xlUp).Row ' The amount of stuff in the column
ReDim eNumStorage(1 To lrow - 1)

For i = lrow To 2 Step -1
    If (Not IsEmpty(Cells(i, 2).Value)) Then ' checks to make sure the value isn't empty
        j = j + 1
        eNumStorage(j) = Cells(i, 2).Value
    End If
Next i

ReDim Preserve eNumStorage(1 To j)

'Not sure what this bit is doing so have left as is
If (IsEmpty(eNumStorage)) Then
    MsgBox ("You did not enter an employee number for which to query our database. Quitting")
    Exit Sub
End If

For j = LBound(eNumStorage) To UBound(eNumStorage)  ' loop through the previous array
    eNumStorage(j) = Replace(eNumStorage(j), " ", "")
    eNumStorage(j) = Replace(eNumStorage(j), ",", "")
Next j

End Sub

【讨论】:

  • 嘿,@SJR。看起来您的解决方案正在运行。非常感谢您的耐心等待并向我解释。
猜你喜欢
  • 2021-01-18
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多