【问题标题】:Run time Error '13' Type Mismatched on using .Find Function in Userform在用户窗体中使用 .Find 函数时运行时错误“13”类型不匹配
【发布时间】:2026-01-05 10:10:01
【问题描述】:

这是我的代码:

Option Explicit
Private Sub CBu_Login_Click()
Dim ws As Worksheet, rng As Range, lrow As Long, find_value As String
Dim cel As Range

Set ws = ThisWorkbook.Sheets("UserName")
lrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Set rng = ws.Range("A2:A" & lrow)
find_value = Me.TB_Username.Value
Set cel = rng.Find(What:=find_value, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
If Not cel Is Nothing Then
    If Me.TB_Password.Value = cel.Offset(0, 1).Value Then
        UF_Encoding.L_User.Caption = "Welcome " & cel.Offset(0, 2).Value & "!" & " You are logged in."
        UF_Encoding.TB_Operator.Text = cel.Offset(0, 2).Value
        UF_Encoding.Show
        Me.Hide
    Else
        MsgBox "Invalid Username/Password"
    End If
Else
    MsgBox "Invalid Username/Password"
End If

End Sub

这段代码在.Find 部分给我一个Type Mismatched 错误。
代码位于Command Button
此外,这有时会起作用,然后突然会抛出Mismatched Error
请帮助它为什么抛出错误以及如何纠正它。
我不想诉诸循环,因为我有很多用户。

【问题讨论】:

  • After:=ActiveCell 更改为After:=ws.Range("A2") 会发生什么?
  • 哇,我一定在打瞌睡,一定错过了这个。哈哈谢谢sid。
  • 书签 THIS LINK FOREVER 或者直到你不再偏离那个时候。
  • 相信我,我确实为它添加了书签。我所有的代码都适应了这一点。有趣的是我没有注意到活动单元。哈哈,我想来杯咖啡比较合适。

标签: vba excel excel-2010


【解决方案1】:

避免使用ActiveCell,除非有绝对必要的理由加入它。

请看THIS LINK

简单的改变

After:=ActiveCell 

After:=ws.Range("A2")

【讨论】:

  • Errors with .Find are usually because LookIn is set wrongly. 我不想这么说,但你的假设是不正确的 :)
  • 你好,席德! :) 唔。我现在实际上正在阅读它。我检查了 MSDN 数据库,似乎 LookIn 比我想象的要多(不知道它甚至需要一个 Variant,哈哈)。但是,每当我个人遇到此问题时,我通常会删除 LookIn 并且它会再次起作用。不过,请随时更正我上面的代码。 ;)
  • Activecell 设置为ws.Range("A2") 解决了这个问题。 Me.TB_Username.Value 是一个字符串。 xlFormulas 工作正常。
  • 感谢您的接受,尽管 Sid 在这里值得称赞,因为仅他的评论就解决了所有问题。 :D
  • + 1 Feel free to correct my code above though. ;) – BK201 2 mins ago 我刚刚做了 :)
【解决方案2】:

一种可能的解决方案。我已经评论了所有内容,以便您可以按照具体步骤操作。

Sub Hide_Me()

    Dim rngHeadings As Range 'the range where your headings are
    Dim arrHideColumns() As Variant 'the array, where you list all headings that should be hidden
    Dim Item As Variant 'a common variable for the for-each-loop
    Dim rngResult As Range 'the range for the search result
    
'Assign the range, where your headings are

    Set rngHeadings = Worksheet1.Range("C3:E3")

'List the headings you want to be hidden

    arrHideColumns = Array("Address", "Phone Number")

'Loop through your list

    For Each Item In arrHideColumns
    
'Use the .FIND method of the range-object
'Please read more about this method here: https://docs.microsoft.com/en-us/office/vba/api/excel.range.find

        Set rngResult = rngHeadings.Find(Item)

'If there is a result

        If Not rngResult Is Nothing Then

'Hide the column

            rngResult.EntireColumn.Hidden = False
            
        End If
    
    Next

End Sub

【讨论】: