【发布时间】:2013-02-14 17:25:57
【问题描述】:
我试图弄清楚如何使用 VBA 从 Excel 数据创建一个数组作为活动列表,当我的脚本通过循环运行时,可以自动添加和删除唯一条目。
例子:
Object# , Status , Group# , Time
1 , Associate , 1 , 1
1 , Associate , 1 , 1.1
1 , Associate , 2 , 2
1 , Associate , 3 , 3
1 , Disassociate , 2 , 4
该数组将填充 Object、Status 和 Group 的唯一组合,但 Time 无关紧要,因为一旦关联对象,它将保持关联,直到取消关联。
我已经在这方面寻求帮助,但大多数帖子只讨论填充数组,并没有讨论循环如何帮助在解除关联时自动删除条目。
所以在这个例子中,我想要一个允许我输入对象 # 和时间的系统,然后脚本会运行,最后它会告诉我“在时间 4,对象 1 与组 1 和3"。另一种情况是“在时间 3,对象 1 与组 1、2、3 相关联”。最后,如果在时间 5 取消所有对象的关联,则消息将显示该对象关联到的最后一个组。
我有一个代码可以完成我需要的一切,直到它遇到一个对象与多个组相关联的情况,然后它无法返回准确的信息。我的编程知识有限,因此感谢您的帮助。下面是我目前拥有的代码,其中 Cells (15, 8) 和 (18, 8) 是 Object # 和 Time 的值输入单元格。
Private Sub CommandButton2_Click()
Dim Association As String, i As Integer, Group As Integer
Count = Application.WorksheetFunction.CountA(Range("A:A"))
For i = 1 To Count
If Cells (i, 1).Value = Cells(15, 8) And Cells (i, 4).Value <= Cells (18, 8) And Cells (i, 2) = "Associate" Then Association = "Associated"
If Cells (i, 1).Value = Cells(15, 8) And Cells (i, 4).Value <= Cells (18, 8) And Cells (i, 2) = "Disassociate" Then Association = "NOT Associated"
If Cells (i, 1).Value = Cells(15, 8) And Cells (i, 4).Value <= Cells (18, 8) And Cells (i, 2) = "Associate" Then Group = Cells(i, 3)
Next i
If Association = "Associated" Then MsgBox Association & " Associated to " & Group
If Association = "NOT Associated" Then Msgbox Association & " Was Last Associated to " & Group
If Association = "" Then Msgbox "Object Does Not Exist Prior to This Time"
End Sub
【问题讨论】:
-
为了简单起见,您能否与我们分享一下已经获得的代码?只需编辑您的问题。
标签: arrays excel list vba for-loop