Excel VBA查找行中的所有值并将不同的列值保存到variables中

我做了相当多的search,找不到符合我的情况的任何代码,或者我可以修改的一点,除了一个。

看下面的电子表格。 我想让用户inputOrderNumber然后searchColumn A的每个值的数字。 就像我想要它将ItemNumberQtyOrdered复制到两个不同的variables,以便稍后将它们放入文本框中。

我希望它将信息“堆栈”到variables中,使之类似于ItemNumValues = ItemNumValues + Cell.Value

电子表格

我试图修改其他人的代码(“他们的代码”),但我得到一个不匹配的types错误。 其余的代码工作。 以前的function中有一些跟踪元素没有被使用,我还没有删除它们。

 '*********************************************************** '********** Their Code Follows ***************** '*********************************************************** Dim numentries As Integer Dim i As Integer '*********************************************************** 'Get number of entries numentries = Worksheets(Sheet1).UsedRange.Rows.Count '************************************************************* 'Run loop to cycle through all entries (rows) to copy For i = 1 To numentries If (Worksheets("Sheet1").Cells(i + 2, 1).Value = InStr(1, Cell, OrderNumber, vbTextCompare)) Then MsgBox Test End If Next i End If '*********************************************************** '********** End Their Code ***************** '*********************************************************** 

我build议使用multidimensional array。 如果你以前从未使用过数组,我强烈build议阅读它们。

 Sub GatherData() Dim c As Range Dim aGetData() As Variant 'This is our array Dim i As Integer Dim a As Integer Dim iRowCount As Integer Dim sRange As String 'Gather data iRowCount = Worksheets("Sheet1").UsedRange.Rows.Count For Each c In Range("A2:A" & iRowCount) If c.Value = 636779 Then ReDim Preserve aGetData(2, i) 'An array must have a set size but as we 'do not know how many order numbers will be found we have to 'resize' 'the array to account for how many we do find. Using "ReDim Preserve" 'keeps any data we have placed into the array while at the same time 'changing it's size. For a = 0 To 2 'Our first index will hold each col of data that is why 'it is set to 2 (arrays start at a base of zero, so '0,1,2 will be each col(A,B,C) aGetData(a, i) = c.Offset(0, a) 'This gets each value from col A,B and C Next a i = i + 1 'Increment for array in case we find another order number 'Our second index "aGetData(index1,index2) is being resized 'this represents each order number found on the sheet End If Next c 'How to read the array For i = 0 To UBound(aGetData()) For a = 0 To 2 Debug.Print aGetData(a, i) Next a Next i End Sub 

看来OrderNumberA列)是sorting的。 非常好的消息(如果他们不是,就把它们整理一下))。 这个简单的函数将得到ItemNumberQtyOrdered到一个二维数组,其中每一行都是它们的一对。

 Function ArrItemQty(ByVal OrderNumber As Long) With Worksheets("Sheet1").UsedRange.Offset(1) .AutoFilter 1, OrderNumber ArrItemQty= .Resize(, 2).Offset(, 1).SpecialCells(xlCellTypeVisible).value .Parent.AutoFilterMode = False End With End Function 

这里有一点testing:

 Sub Test() Dim i As Long, j As Long, ar ar = ArrItemQty(636779) For i = LBound(ar, 1) To UBound(ar, 1) Debug.Print For j = LBound(ar, 2) To UBound(ar, 2): Debug.Print ar(i, j),: Next Next End Sub 

请注意,生成的数组是基于1的。 使用LBoundUBound是最安全的。