如何find值并在VB中创build它们的数组excel?

我有这个问题。 我必须在一column ("E")find非空白单元格,并将它们放入数组中,然后列出该数组。 我试过这个,但数组没有正确填充

  Dim k As Integer Dim X() As String k = 0 dimX = Application.CountA(Range("E2:E2498")) ReDim X(1 To dimX) For i = 2 To 2498 If IsEmpty(Cells(i, "E")) Then k = k + 1 X(k) = Cells(i, "E").Value End If Next i 

我已经重写了这个代码来优化速度,即:

  • testing前面是否有任何列E条目
  • 使用SpecialCells立即返回公式和常量的范围
  • 使用变体数组来处理列E的使用部分的每个区域( Xvariables),然后写入单个二维输出数组Y

请注意,这段代码重新生成单元格中的值,无论它们是基于常量的公式。 它可以很容易地更新,通过更改返回公式

  1. X = rngArea.Value2X = rngArea.Formula
  2. Y(lngRowTot) = rngArea.Value to Y(lngRowTot) = rngArea.Formula

示例输出

代码示例

  Sub GetEm() Dim rng1 As Range Dim rng2 As Range Dim rngFinal As Range Dim rngArea As Range Dim X Dim Y Dim lngRow As Long Dim lngRowTot As Long 'early exit if there are no values If Application.CountA(Columns("E")) = 0 Then MsgBox "Column E has no formulae or constants", vbCritical Exit Sub End If 'quickly determine the range of constants and formulae On Error Resume Next Set rng1 = Columns("E").SpecialCells(xlFormulas) Set rng2 = Columns("E").SpecialCells(xlConstants) On Error GoTo 0 If Not rng1 Is Nothing Then If Not rng2 Is Nothing Then Set rngFinal = Union(rng1, rng2) Else Set rngFinal = rng1 End If Else Set rngFinal = rng2 End If ReDim Y(1 To 100) 'Look at each range area (data may not be continuous) For Each rngArea In rngFinal.Areas 'Use variant arrays to popluate a single dimension string array If rngArea.Cells.Count > 1 Then X = rngArea.Value2 For lngRow = 1 To UBound(X) lngRowTot = lngRowTot + 1 If lngRowTot Mod 100 = 0 Then ReDim Preserve Y(1 To (UBound(Y) + 100)) Y(lngRowTot) = X(lngRow, 1) Next Else 'handle single cells lngRowTot = lngRowTot + 1 If lngRowTot Mod 100 = 0 Then ReDim Preserve Y(UBound(Y) + 100) Y(lngRowTot) = rngArea.Value End If Next 'cut down array to require size ReDim Preserve Y(1 To lngRowTot) MsgBox Join(Y, ", "), , "Your array is" End Sub 

您可能想要检查单元格是否不是空的:

尝试改变:

 If IsEmpty(Cells(i, "E")) Then 

至:

 If Not IsEmpty(Cells(i, "E")) Then 

顺便说一句,你应该在你的代码开始时使用Option Explicit强制variables声明。 您将然后添加:

 Dim i As Integer, Dim lSize As Long 

注意:我用一个lSize var代替了你的dimX var,因为Dim dimX让我哭了。