VBA 循环访问名称列表并执行功能.在第二个循环开始时,最后一个循环结束



下面的代码在每个循环结束时都运行良好,我称之为"洗牌模块",它随机洗牌列表中的名称,并继续循环,该循环随机化人员分配到每个日期的顺序,但是由于人们并不总是有空,我发现人们被分配到连续的日期,这不是必需的。与其"洗牌"列表,不如依次分配。 我正在努力解决的问题是如何依次循环浏览姓名列表,以及何时进行下一次日期分配,从列表中的下一个人开始。所以试着更容易解释一下。

名称列表在 A 列中假设 1-20 B 列有日期 C 列有日期 D 列有日期

约会 B 需要 3 人,约会 C 需要 2 个人,约会 D 需要 5 个人。 目前,分配从人员 1 开始检查他们是否有空,然后它会将它们分配到该日期并移动到人员 2,依此类推。 假设人员 1、2 和 3 在该日期都可用,那么人员 1、2 和 3 将被分配到该日期。 当该列的分配完成后,程序移动到 B 列,这里需要发生的是,可用性检查应该从人 4 开始,但我的代码再次从人 1 开始。这不是我想要的,检查必须从列表中的下一个人开始,而不是再次回到开始时。有没有人能够建议我如何调整此代码以使其满足我的要求。希望一些善良的灵魂可以帮助我解决这个问题,因为我完全被困住了。感谢您抽出宝贵时间查看本文

Public Sub copyothers()
Dim listofcells As Range
Dim currentname As String
Dim foundrow As Integer
Dim foundcolumn As Integer
Dim counter As Integer
Dim i As Integer
Dim personcount() As Variant

Sheets("Availability").Activate
personcount = Sheets("Availability").Range("B3:AR3").Value 'check the number 
of people required in each column and record it for later
For i = 2 To 44
Sheets("Availability").Activate
Sheets("Availability").Range("a2").Select
counter = personcount(1, i - 1) - 1 'take the first number reduce it by 1 and move one column right right each time program loops
If Not Sheets("Availability").Cells(2, i) = "" Then
Sheets("Availability").Range(Cells(2, i), Cells(2, i).End(xlDown)).Select
Else
GoTo skip:  'If the column has no data then skip to next column
End If
Set listofcells = Selection
Sheets("allocation").Activate
Range("a2").Select

For Each singlecell In listofcells
If counter > 0 Then
If singlecell = "Available" Then
foundcolumn = singlecell.Column 'record the column number where "Available" was found
currentname = Sheets("Availability").Range("A" & singlecell.Row) 'record the name of the person in the row where "Available" was found
Set foundName = Sheets("Allocation").Range("A:A").Find(What:=currentname, LookIn:=xlValues) 'find the persons name in "Allocation" sheet
foundrow = foundName.Row
If Sheets("allocation").Cells(foundrow, foundcolumn) = "" Then
Sheets("allocation").Cells(foundrow, foundcolumn) = "X" 'place X in the same cell as it appeared in "Availability" sheet
counter = counter - 1
End If
End If
End If
Next singlecell
skip:
Call Shuffle
Next i
End Sub

不幸的是,由于声誉不佳,我不能发表评论,但是我有几个问题。在你的如果不是/那么声明中,你为什么叫"跳过"?要转到下一列,简单地让 else 部分空白可能会更有效。另外,代码的"跳过:"部分中的"随机播放"的目的是什么?

另外,您可以尝试的一件事是代替

For singlecells in listofcells
*Code
Next Singlecell

尝试

For singlecells + marker in listofcells
*Code
mixer = mixer + 1
Next Singlecell

"标记"应该阻止你的程序再次重复每个人。

最新更新