循环访问列并将值从单元格复制到数组中

所以我真的是新的excel,我试图将一个单元格中的一些值复制到一个数组,然后显示列中的数组。 所以我所拥有的是列名(A)中的名字列表。然后我在列(B)中的名字旁边有一个数字列表。 所以我想要做的是通过数字循环,如果任何数字等于4.将数字对应的名称复制到我的数组中。 并稍后显示该数组让我们在D列说。这是我迄今为止。

Option Explicit Public Sub loopingTest() Dim FinalRow As Long ' Dim i As Long 'varable that will loop through the column Dim maxN As Integer 'variable that will hold the maximum number Dim j As Long 'variable that will hold the index of the array Dim ArrayTest As Variant FinalRow = Cells(Rows.Count, 1).End(xlUp).Row ' will get the last row For i = 1 To FinalRow 'loop until the last row If Range("B" & i) = 4 Then 'if any of the values of column B matches 4 then ArrayTest(j) = Range("A" & i) 'copy the value corresponding to column A to the array j = j + 1 'increment array index End If 'end of endif Next i 'increment column 'output array into column D For x = 1 to FinalRow Range("D" & x) = ArrayTest(x) Next x End Sub 

这是否是正确的方法呢? 此外,如果我想更新列B到任何数字,我会喜欢列D自动更新。 任何帮助,将不胜感激

使用WorksheetFunction.Transpose(Array)方法将数组打印到电子表格。 这是一种广泛用于将数组一次性打印到电子表格的高效( 内置 )方法。

避免像“ End if 'end of end if这样的注释End if 'end of end if任何人阅读你的代码就已经知道了。 更多关于DRY原则。

VBA数组的缺点是你总是需要在创build时指定大小。 这是一个很长的话题,还有其他的方法,避免数组等,但我不打算在这里讨论。 解决方法是从0开始,然后在使用ReDim Preserve调整( 增加 )数组的大小

 Public Sub loopingTest() Dim lastRow As Long Dim i As Long ReDim ArrayTest(0) FinalRow = Cells(Rows.Count, 1).End(xlUp).Row ' will get the last row For i = 1 To lastRow If Range("B" & i) = 4 Then 'if any of the values of column B matches 4 then ArrayTest(UBound(ArrayTest)) = Range("A" & i) 'copy the value corresponding to column A to the array ReDim Preserve ArrayTest(UBound(ArrayTest) + 1) End If Next i Range("D1:D" & UBound(ArrayTest)) = WorksheetFunction.Transpose(ArrayTest) End Sub 

现在是你的代码的简短版本

 Public Sub loopingTest() Dim i As Long: ReDim ArrayTest(0) For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row If Range("B" & i) = 4 Then ArrayTest(UBound(ArrayTest)) = Range("A" & i) ReDim Preserve ArrayTest(UBound(ArrayTest) + 1) End If Next i Range("D1:D" & UBound(ArrayTest)) = WorksheetFunction.Transpose(ArrayTest) End Sub 

更新:

你可以使用一个variables而不是4

 Public Sub loopingTest() Dim lastRow As Long Dim myNumber as Long myNumber = 5 Dim i As Long ReDim ArrayTest(0) FinalRow = Cells(Rows.Count, 1).End(xlUp).Row ' will get the last row For i = 1 To lastRow If Range("B" & i) = myNumber Then ArrayTest(UBound(ArrayTest)) = Range("A" & i) ReDim Preserve ArrayTest(UBound(ArrayTest) + 1) End If Next i Range("D1:D" & UBound(ArrayTest)) = WorksheetFunction.Transpose(ArrayTest) End Sub 

纯粹的信息,你可以做同样的事情没有循环使用类似的东西

 Public Sub nonloopingTest() Dim lastRow As Long Dim myNumber As Long Dim vOut myNumber = 5 lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' will get the last row vOut = Filter(ActiveSheet.Evaluate("TRANSPOSE(if(B1:B" & lastRow & "=" & myNumber & ",A1:A" & lastRow & ",""||""))"), "||", False) If UBound(vOut) > -1 Then Range("D1").Resize(UBound(vOut) + 1) = WorksheetFunction.Transpose(vOut) End Sub