循环遍历列,将值存储在数组中

问题描述 投票:3回答:2

早上好,

我试图找到一种方法:

  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
vba excel-vba excel
2个回答
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

3
投票

这是将列添加到数组的最简单方法:

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
© www.soinside.com 2019 - 2024. All rights reserved.