【发布时间】:2014-08-18 00:38:27
【问题描述】:
如果我创建了一个集合,我可以从集合中搜索该集合并返回索引编号吗?
由于我的新手状态,我无法发布我正在尝试做的截图,所以让我尝试解释一下我想要完成的内容:
我有一个 Excel 格式的仓库数据库的历史记录,它有几千行长——每行代表一个产品进出多达 10 个不同箱子的交易。我的目标是识别数千行中所有可能的不同 bin,将这 10 个 bin 复制/转置到列标题,然后遍历每笔交易并将交易数量(+1、-3 等)复制到正确的列,因此能够分离交易并更容易地识别和生成产品何时进出每个相应箱的会计。这有点看起来像一个数据透视表,但这并不是它真正的工作方式。
这是我目前正在使用 cmets 编写的代码。最后一条评论解释了我的问题:
Sub ForensicInventory()
Dim BINLOCAT As Collection
Dim Rng As Range
Dim Cell As Range
Dim sh As Worksheet
Dim vNum As Variant
Dim BINcol As Integer
Dim ACTcol As Integer
Dim QTYcol As Integer
Dim i As Integer
Dim lastrow As Long
Dim x As Long
'This part is used to find the relevant columns that will be used later
BINcol = ActiveSheet.Cells(1, 1).EntireRow.Find(What:="BINLABEL", LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
ACTcol = ActiveSheet.Cells(1, 1).EntireRow.Find(What:="ACTION", LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
QTYcol = ActiveSheet.Cells(1, 1).EntireRow.Find(What:="QUANTITY", LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
i = 0
Set sh = ActiveWorkbook.ActiveSheet
Set Rng = sh.Range(sh.Cells(2, BINcol), sh.Cells(Rows.Count, BINcol).End(xlUp))
Set BINLOCAT = New Collection
'This next section searches the bin column and builds the collection of unique bins that I am interested in.
On Error Resume Next
For Each Cell In Rng.Cells
If Len(Cell.Value) <> 8 And Not IsEmpty(Cell) Then
BINLOCAT.Add Cell.Value, CStr(Cell.Value)
End If
Next Cell
On Error GoTo 0
'Now I take those unique bin names and I put them into a column header on the same spreadsheet, starting in column 10, and spacing every 2 cells thereafter.
For Each vNum In BINLOCAT
Cells(1, 10 + i).Value = vNum
i = i + 2
Next vNum
'Here is where the problem exists for me. This code works and succeeds in copying the QTY
'to column 10, but what I really want to do is determine the index number of the bin from BINLOCAT,
'and use that index number to place the value under the appropriate column header.
For x = 2 To lastrow
Select Case Cells(x, ACTcol).Value
Case "MOVE-IN"
Cells(x, 10).Value = Cells(x, QTYcol).Value
Case "MOVE-OUT"
Cells(x, 10).Value = -Cells(x, QTYcol).Value
Case Else
End Select
Next x
End Sub
在“For x = 2 to lastrow”循环中,我需要找到一种方法来通过在集合 BINLOCAT 中搜索 bin 来获取 INDEX 编号(1、2、3 等)。 BINLOCAT 一旦创建,就是静态的。我的设想是:
neededcolumn = BINLOCAT.item(cells(x,BINcol).value).index (pseudocode)
然后我会将 Case Stmt 中的 10 替换为“neededcolumn”,这样就可以了。
也许我采用了错误的方法,但在我看来,我需要集合才能有效地进行搜索部分。任何想法或解决方案的链接?根据我在其他地方所读到的内容,我认为我所描述的这种能力不可用,但我不确定我是否已经理解了迄今为止我所读到的关于集合的所有内容。
【问题讨论】:
标签: excel collections indexing key vba