Excel VBA .Find Function changing values in selection

Excel VBA .Find Function changing values in selection

嘿,这可能很简单,但我不知道哪里出了问题。

我正在尝试为特定日期执行 .find,并将 selection 更改为用户输入的日期。

我有一个用户表单 select 来自组合框的日期 (date1_cbo)。组合框源链接到工作表(后端)上的日期。下面有一个文本框,用于写入新日期以将其更改为 (date1_txt)。我一直收到错误

object variable or with block variable not set.

我已经尝试了几个选项,但都没有成功,这是我的代码:

Dim selection As Range
Dim check As Boolean

'input box validation
check = IsDate(date1_txt.Value)
If check = True Then
    'find cell matching combobox
    With Worksheets("Backend").Range("A1:A500")
        Set selection = .Find(date1_cbo.Value) 'this is the problem
        selection.Value = date1_txt.Value
    End With
Else
End If

有趣的是。找到 returns 范围或无。但是,因为组合框链接到我正在搜索的单元格,所以永远不会 return 什么都没有...我不明白为什么会发生错误。

您正在使用一个名为 Selection 的变量。 VBA 也使用它。将您的变量重命名为其他任何名称,重写您的代码,它应该可以工作。即使 Selection1 也很好:

Public Sub TestMe()

    Dim selection1 As Range
    With Worksheets(1).Range("A1:A500")
        Set selection1 = .Find("vi")
    End With

    If Not selection Is Nothing Then
        selection1.Value = "some other value"
    End If

End Sub

要像这里一样用 Find() 更改多个值 - A1:A10,那么一些可能性是这样做的:

Public Sub TestMe()

    Dim myRng As Range

    With Worksheets(1).Range("A1:A500")
        .Range("A1:A10") = "vi"
        Set myRng = .Find("vi")
        If Not myRng Is Nothing Then
            Do Until myRng Is Nothing
                myRng.Value = "New value"
                Set myRng = .Find("vi")
            Loop
        End If
    End With

End Sub

有点慢,每次都是循环,如果统一range,一次性替换,还可以改进

名为 'selection' 的变量是错误的编码习惯,但完全合法。为了清楚起见,请勿使用此类名称。


当您尝试从空对象读取 属性( .value) 时会导致错误 91。您的选择变量为空,因为 sheet 和组合框上的日期格式不同。


在尝试在 sheet 中找到它之前,只需转换为日期。 Set selection = .Find(CDate(date1_cbo.Value)) '/ once again, selection is valid but bad name for variable.