【问题标题】:Find returns nothing even if value exists即使值存在,Find 也不返回任何内容
【发布时间】:2019-11-19 22:21:40
【问题描述】:

所以这里我有关于 find 方法的第 n 个问题。我已经阅读了很多关于它的问题以及它带来的问题,但仍然找不到解决我的问题的方法。

我只想返回特定值(日期)的行数和列数。但是,代码总是运行相同的 91 错误(未设置对象变量),因为 find 方法找不到任何内容。

我试图将变量定义为范围并通过设置变量来更改代码(即设置 daterow = 等)。但问题依然存在。

Sub actual_cash_flow()
Dim cfdate As Long
Dim today As Long
Dim daterow As Long
Dim datecolumn As Long

today = Date
cfdate = WorksheetFunction.EoMonth(today, -1)

daterow = Sheet2.Cells.Find(What:=cfdate, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, searchformat:=False).Row
datecolumn = Sheet2.Cells.Find(What:=cfdate).Column


End Sub

我想知道行数和列数,以便识别单元格,然后执行一些操作。

编辑:

通过按照@mikku 的建议编辑代码并调试代码中定义的值和变量的范围,我得到了相同的值,但是,我仍然没有得到任何输出。所以我真的不知道错误在哪里。看图。

【问题讨论】:

标签: excel vba


【解决方案1】:

正如我在对上一个问题的回答中指出的那样,使用日期和 Range.Find 函数可能会很棘手。原因之一似乎是 VBA Date 数据类型与 Excel 工作表中存储的日期不同。后者是一个Double,格式看起来像一个日期。

因此,特别是如果您希望 .Find 方法独立于日期设置,您最好不要使用 Range.Find 方法,而是循环访问数据。

在下面的代码中,我展示了这可能如何工作的示例,根据您提供的工作簿进行假设,并使用 VBA 数组,因为这将比在工作表上的范围内循环运行更快:

Sub actualcf()

Dim cfdate As Long  'Yes --Long for this application
Dim daterow As Long
Dim datecolumn As Long
Dim fnd As Range

Dim srchRng As Range
Dim vSrch As Variant
Dim I As Long

With Worksheets("Peschiera CF")

'Find the row with the dates
Set srchRng = .Cells.Find(what:="Yr. Ending", after:=.Cells(1, 1), LookIn:=xlValues)

'Read that row into a VBA array, but only the columns with data
'Note that we are using `.Value2` which has no formatting
If Not srchRng Is Nothing Then
    vSrch = .Range(.Cells(srchRng.Row, 1), .Cells(srchRng.Row, .Columns.Count).End(xlToLeft)).Value2
End If

cfdate = WorksheetFunction.EoMonth(Date, -1)
For I = 1 To UBound(vSrch, 2)
    If vSrch(1, I) = cfdate Then
        daterow = srchRng.Row
        datecolumn = I
    End If
Next I

End With
End Sub

【讨论】:

    【解决方案2】:

    这段代码应该可以工作:

    Sub actual_cash_flow()
    
    Dim cfdate As Date
    Dim daterow As Long
    Dim datecolumn As Long
    Dim fnd As Range
    
    cfdate = WorksheetFunction.EoMonth(Date, -1)
    
    Set fnd = Worksheets("SheetName").Cells.Find(What:=cfdate, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, searchformat:=False)
    
    If Not fnd Is Nothing Then
    
        daterow = fnd.Row
        datecolumn = fnd.Column
    
    End If
    
    End Sub
    

    在代码中输入您的工作表名称。

    问题在于变量的设置,你应该在搜索日期时将它们声明为日期。

    【讨论】:

    • 不。它什么也不返回。如果我在 excel 中搜索变量为 30-Jun-19 然后它找到它,那么代码肯定有问题。
    • "dd-mmm-yy" 所以 2019 年 6 月 30 日是 30-Jun-19
    • 你需要分享你的工作簿,否则我不明白为什么它不起作用
    • 你在这里sample
    猜你喜欢
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2020-01-26
    • 2018-10-02
    • 2019-03-22
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多