计算单元格列中的行

时间:2019-02-24 20:22:55

标签: excel vba

我正试图遍历每个工作人员名册,并自动将他们安排为免费会议。部分原因是对当前单元格(会话)列中的行进行计数

名册数据看起来像 enter image description here

会话数据如下

enter image description here

到目前为止的代码是:

Sub ScheduleSession()
Dim Roster As Worksheet
Dim Sessions As Worksheet
Dim LastRow As Long
Dim x As Long
Dim row As Range
Dim Session As Range

With ActiveWorkbook.Worksheets("Roster")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).row
For x = LastRow To 8 Step -1

    If IsEmpty((.Range("B" & x))) Then
        ' Look for a session
        Debug.Print ("Looking For a Session for " & (.Range("A" & x)))
                For Each Session In ActiveWorkbook.Worksheets("Sessions").Range("A1:E1").Cells
                    Debug.Print (Session)
                    ' Check session is not full (3 per session) else next session
                    SessionCount = Cells(Rows.Count, Session.Columns.Count).End(xlUp).row
                    If (SessionCount > 4) Then
                        Exit For
                    Else
                        ' Loop over cells in employee roster to see if they are working on given day and time.
                        ' If so roster them by recording session against employee (on ROSTER col B) and employee against session in appropriate col on SESSIONS
                    End If
                Next

    Else
        ' Employee already scheduled
        Debug.Print ("This employee " & (.Range("A" & x)) & " already has a session")
    End If

Next x
End With

在为每个会话循环行中的行进行计数时,请问我可以得到帮助,当前行是运行时错误91-未设置块变量的对象变量。

这个问题已经回答了很多次,但是我看到的其他答案并没有说明如何将其应用于Session等范围。

如果任何人都愿意在每次会议上前往员工名册以检查他们是否在工作并且是否可以安排时间表,那将是很好的指导。

更新:抱歉的会话是会话

SessionCount = Cells(Rows.Count, Session.Columns.Count).End(xlUp).row

因为在For Each会话循环中需要当前会​​话中的行数。

2 个答案:

答案 0 :(得分:1)

我认为您尚未设置变量Sessions。在Dim Sessions As Worksheet之后的某处,您需要添加Set Sessions = ActiveWorkbook.Sheets("Sessions")

答案 1 :(得分:1)

SessionCount = Cells(Rows.Count, Session.Columns.Count).End(xlUp).row

Session是一个单元格,因此您总是在看第一列...

SessionCount = Cells(Rows.Count, Session.Column).End(xlUp).row

...可能就是您想要的