为什么我收到此错误:对象变量或未设置块变量?

时间:2014-09-02 21:11:14

标签: excel vba excel-vba

我已经找到导致此错误的原因,但我无法确定它在我的代码中的来源。我甚至在excel的单独工作表中测试了这个宏并且它工作但是在这个工作表中它不起作用。任何人都可以猜测为什么或提供任何变通方法?我在错误的行上发表评论。假设数据正确放入。

Private Sub CommandButton1_Click()
    Dim startDate As Date, endDate As Date, reason As String, name As String
    name = InputBox("Please enter the name of the SLG as appears in column 1 on the worksheet:")
    startDate = InputBox("Please enter the start date in MM/DD/YYYY format:")
    endDate = InputBox("Please enter the end date in MM/DD/YYYY format:")
    reason = InputBox("Please short description for the absence:")

    Dim rng1 As Range, columnNumberStart As Integer, rowNumber As Integer, columnNumberEnd As Integer, test1 As String, test2 As String

    Worksheets("FY-15 Schedule").Activate

    Set rng1 = ActiveSheet.UsedRange.Find(name)
    rowNumber = rng1.Row

    Set rng1 = ActiveSheet.UsedRange.Find(startDate) 
    columnNumberStart = rng1.Column 'Says Error is on this line

    Set rng1 = ActiveSheet.UsedRange.Find(endDate)
    columnNumberEnd = ActiveSheet.UsedRange.Find(endDate).Column

    test1 = Cells(rowNumber, columnNumberStart).Address
    test2 = Cells(rowNumber, columnNumberEnd).Address

    Dim rng2 As Range
    Set rng2 = Range(test1, test2)


    rng2.Value = reason

End Sub

2 个答案:

答案 0 :(得分:2)

首先,明确强制输入框输入中的日期:

startDate = CDate(InputBox("Please enter the start date in MM/DD/YYYY format:"))

对其他日期字段执行相同操作。

然后,仍然存在同样错误的来源:当.Find方法已将Nothing返回到范围对象时(例如,找不到日期/不存在)在表格中)然后你基本上做Nothing.Column,这是一个错误。

如果工作表中不存在日期,这将始终引发错误,您可以像这样陷阱,或使用GoTo语句返回输入框等...

Set rng3 = ActiveSheet.UsedRange.Find(startDate) 
If rng3 Is Nothing Then 
    MsgBox "Start date" & Cstr(startDate) & " not found!", vbInformation
    Exit Sub
End If
columnNumberStart = rng1.Column 

答案 1 :(得分:0)

我明白了!问题是:没有找到日期,因为日期是由公式生成的!我的第一个日期是手动输入的,但其余的是第二个单元格的填充系列,它是A2=A1+1并且一直在线下。我希望这样,所以开始日期可以改变,但出于某种原因,excel并没有将这些视为日期!?!有多奇怪?!?!

虽然问题解决了。你所说的是正确的,因为它没有找到日期,但在看电子表时看起来很明显,但在查看单元格时,它们的值是公式。