我已经做了很多搜索,找不到符合我情况的代码或者我可以修改的代码除外。
查看下面的电子表格。我想让用户输入OrderNumber
,然后搜索Column A
以查找该号码的每个值。因为它,我希望它将ItemNumber
和QtyOrdered
复制到两个不同的变量,以便稍后将它们放入文本框中。
我想要"堆叠"将信息转换为变量,如ItemNumValues = ItemNumValues + Cell.Value
我尝试修改其他人的代码("他们的代码")但是我收到了不匹配类型的错误。其余的代码工作。脚本中有一些跟踪元素来自之前没有使用过的功能,我还没有删除它们。
'***********************************************************
'********** 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 *****************
'***********************************************************
答案 0 :(得分:1)
我建议使用多维数组。如果您以前从未使用过数组,我强烈建议您阅读它们。
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
答案 1 :(得分:1)
似乎OrderNumber
(列A
)已排序。非常好的消息(如果他们不是,只需对它们进行排序;))。这个简单的函数可以将ItemNumber
和QtyOrdered
转换为二维数组,其中每一行都是一对。
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
这是一个小小的测试:
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
P.S。请注意,生成的数组是从1开始的。如上所示,使用LBound
和UBound
是最安全的。