为什么这个VBA循环找到空单元格删除标题行值?

时间:2017-06-02 18:50:06

标签: excel vba

我有一个工作簿,每个分支机构都有自己的标签。每个选项卡都有可用日期的行标题,以及可用时间的列标题。屏幕加盖如下:

enter image description here

从那里我使用用户表单从下拉列表中收集分支名称(通过循环显示表单的名称填充),可用日期(获取已识别表单上的日期),然后是空白时间对于给定的日期。

出于某种原因,每次选择日期时,都会将日期单元设置为""或空白。任何人都可以验证我的语法吗?我无法告诉它可能将它设置为空白...谢谢!

Option Explicit
Public Sub UserForm_Initialize()Dim sht As Worksheet
    'clear form
    BranchBox.Value = ""
    DateBox.Value = ""
    TimeBox.Value = ""

    'populate sheet names from each branch
    For Each sht In ActiveWorkbook.Sheets
      Me.BranchBox.AddItem sht.Name
    Next sht
End Sub
Public Sub BranchBox_Change()
    'populate dates
    Me.DateBox.List = Worksheets(BranchBox.Value).Range("A2:A31").Value
End Sub
Public Sub DateBox_Change()
    Dim dateSel As String
    Dim branch As String
    Dim sht As Worksheet
    Dim cel As Range
    Dim matchingHeader As Range

    branch = BranchBox.Value
    Set sht = ActiveWorkbook.Worksheets(branch)
    dateSel = DateBox.Value

    'Get Row to scan
    Dim i As Long, rowOff As Long
    For i = 2 To sht.Rows.Count
        Set cel = sht.Cells(i, 1)
        If cel.Value = dateSel Then
            rowOff = i
            Exit For
        End If
    Next i

    'Scan selected row for blank cells
    Dim cnt As Integer
    For i = 2 To sht.Columns.Count
        cel = sht.Cells(rowOff, i)
        If CStr(cel.Value) = "" Then
            Set matchingHeader = sht.Cells(1, i)
            TimeBox.AddItem matchingHeader.Value
        End If
    Next i

    Me.TimeBox.AddItem ("No Appointments Available")
End Sub

1 个答案:

答案 0 :(得分:1)

你的行

cel = sht.Cells(rowOff, i)

隐含

cel.Value = sht.Cells(rowOff, i).Value

我相信你的意思是

Set cel = sht.Cells(rowOff, i)