2012-01-03 59 views
1

我遇到問題了。我必須在一個column ("E")中找到非空白單元格,並將它們放入數組中,然後列出該數組。我想這一點,但數組未正確填寫如何在VB excel中查找值並創建它們的數組?

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 
+0

什麼樣的陣列,單維數字符串數組,二維數組等? E列中是否有公式單元格和/或常量(文本字符串或硬編碼數字)? – brettdj 2012-01-03 10:11:14

+0

現在運行你的代碼(doh)罷工我的第一個問題....上面的代碼將運行在兩個公式/值和返回值(如我的代碼下面) – brettdj 2012-01-03 10:52:17

回答

2

您可能要檢查電池空:

嘗試改變:

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

到:

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

順便說一句,你應該在開始時使用Option Explicit的代碼強制變量聲明。然後,您可以添加:

Dim i As Integer, 
Dim lSize As Long 

注:我已經被lSize VAR代替你dimX變種,因爲Dim dimX是讓我哭。

+0

:) :)謝謝! – user1111530 2012-01-03 10:40:26

3

我已經重寫這段代碼optimixe即速度:

  • 檢測是否有E列條目前面使用SpecialCells立即返回使用變形公式的範圍和常量
  • 陣列來處理列E的使用部分的每個區域(變量爲X),然後寫入單個二維輸出陣列Y

請注意,此代碼重新生成單元格中的值,無論它們是基於常量的公式。它可以很容易地更新,通過改變

  1. X = rngArea.Value2X = rngArea.Formula
  2. Y(lngRowTot) = rngArea.Value返回公式Y(lngRowTot) = rngArea.Formula

樣本輸出

code sample

代碼

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 
+0

不錯的。當我回答這個問題時,我嘗試了一個'array = Columns(「E」)。SpecialCells(xlConstants).Value',它沒有工作,因爲它停在第一個空值(想避免任何循環)。不錯的代碼雖然:) – JMax 2012-01-03 11:53:24

相關問題