【问题标题】:Find Function Not Working On Second Run of Macro查找函数在第二次运行宏时不起作用
【发布时间】:2018-12-09 13:28:57
【问题描述】:

我正在使用 Excel 2013 并在几秒钟前运行一次宏后再次运行它。

在我第一次运行时,宏名义上运行。但是,如果我尝试第二次运行它,我的代码的一部分(主要是使用 range.find)在我期望它找到某些东西时什么也不返回。

有问题的代码:

If facilsheet.Cells(d.Row, d.Column + 2).Value <> vbNullString Then
   If facilsheet.Cells(d.Row, d.Column + 2).Value <> "--" Then
       net_event = facilsheet.Cells(d.Row, d.Column + 2).Value
       net_event = CDate(net_event)
       Debug.Print net_event
       Debug.Print "net_event is  a " & TypeName(net_event)
       Debug.Print timelinesheet.Cells(3, 4).Value
       Debug.Print "timelinesheet cell is " & TypeName(timelinesheet.Cells(3, 4).Value)
       Set rng2 = timelinesheet.Range("3:3").Find(what:=net_event, MatchCase:=False)
    End if
End If

第一次运行代码(名义情况,一切正常时),调试返回:

2016 年 9 月 6 日
net_event 是一个字符串
2016 年 9 月 6 日
时间表单元格是一个日期

而 rng2 不是 Nothing。

我第二次运行这个,调试返回和上面一样的东西,但是 rng2 什么都没有。

我尝试明确说明 Find 的所有参数,看看是否可行。

'timelinesheet' 是一个公共变量。这可能是一个公共变量问题吗?在我的宏中还有其他地方,我将 find 与“timelinesheet”一起使用,并且在第二次运行期间一切正常。

【问题讨论】:

  • 当你第二次运行它时,你得到net_event的任何值吗?
  • 嗨,扎克,是的,我愿意。该值为 2016 年 9 月 6 日(如预期)
  • 你能不能把timelinesheet.range ...改成Woksheets("&lt;whatever your sheet name is&gt;").Range ...试试看
  • 我尝试了 Worksheets("Timeline").Range("3:3 ").Find(what:=net_event,MatchCase:=False‌​) 但也没有任何乐趣。
  • 这不是“条件格式”...您在时间线表的某些单元格中写“NET”,即rng2 属于同一张表!检查你没有覆盖 rng2。 BTW rng2 应该是一个单元格范围,那么循环遍历其单元格有什么用?

标签: excel vba


【解决方案1】:

我严重怀疑这是一些 cmets 中提到的公共变量问题。

这对我有用:

Sub test()

    Dim facilsheet As Excel.Worksheet, timelinesheet As Excel.Worksheet
    Dim net_event, rng2 As Range

    ' for testing purposes only
    Set facilsheet = ThisWorkbook.Sheets(1)
    Set timelinesheet = ThisWorkbook.Sheets(2)

    net_event = facilsheet.Cells(1, 1).Value

    ' purposely commented out 
    'net_event = CDate(net_event)

    Debug.Print net_event
    Debug.Print "net_event is  a " & TypeName(net_event)
    Debug.Print timelinesheet.Cells(3, 4).Value
    Debug.Print "timelinesheet cell is " & TypeName(timelinesheet.Cells(3, 4).Value)
    Set rng2 = timelinesheet.Rows(3).Find(what:=net_event, MatchCase:=False) ' notice I changed Range to Rows

    Debug.Print "rng2.Address: " & rng2.Address

End Sub

我怀疑您的问题是由于我已注释掉的行中的日期转换以及因为有问题的一个/两个单元格的格式在执行之间发生了变化。如果我在 sub 的执行之间更改 net_value 单元格的格式并进行 net_event 的日期转换,我可以重新创建您的问题,但如果我将这行代码注释掉,则不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多