2017-12-18 193 views
3

早上好,遍歷列,

我試圖找到一種方式來存儲值的數組:通過一列

  1. 迴路(B柱)
  2. 取值,商店他們在一個數組
  3. 遍歷數組,並做一些文字處理

但是,我不能想辦法來循環THROU gh列並將這些值存儲在一個數組中。我已經通過堆棧溢出和谷歌,但還沒有找到一個成功的解決方案(還)。

提前,謝謝你的幫助。

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

什麼特別是你掙扎着 - 有很多網上關於從一個範圍內創建一個數組? – SJR

+0

我已經嘗試了幾種不同的方法,但使用輸入的10個員工數字的測試數據樣本,我還沒有找到一種方法將它存儲到數組中。 @SJR – bm0r3son

回答

2

Ju在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 
+1

嗨,@SJR。它看起來像你的解決方案正在工作。非常感謝您的耐心並向我解釋這一點。 – bm0r3son

2

這是讓列陣列的最簡單的方法:

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 

它從B1值來B10陣列,它給可能性「東西」添加到這個陣列。

Transpose()函數採用單列範圍並將其作爲一維數組存儲。如果數組是在同一行上,那麼你會需要一個雙轉置,使之成爲一維數組:

With Application 
    myArray = .Transpose(.Transpose(Range("A1:K1"))) 
End With 
+0

你能解釋一下Transpose函數在做什麼嗎?它是否默認將每個單元存儲爲數組中的值? – bm0r3son

+0

@TonyKelly - 查看編輯。 – Vityata

+1

謝謝你解釋。我在發佈之後不久就看到了MSDN文章。這非常有幫助。 – bm0r3son