我试图找到一种方法:
但是,我想不出一种方法来遍历一列并获取这些值,并将它们存储在一个数组中。我已经浏览了 Stack Overflow 和谷歌,但没有找到成功的解决方案。
在此先感谢您的帮助。
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
Run Code Online (Sandbox Code Playgroud)
这是获取列到数组的最简单方法:
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
Run Code Online (Sandbox Code Playgroud)
它采用的值从B1到B10阵列,它给可能性“东西”添加到这个阵列。
该Transpose()函数采用单列范围并将其存储为一维数组。如果数组在单行上,那么您将需要一个双转置,以使其成为一维数组:
With Application
myArray = .Transpose(.Transpose(Range("A1:K1")))
End With
Run Code Online (Sandbox Code Playgroud)
只需在 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15699 次 |
| 最近记录: |