【问题标题】:Type Mismatch Error Excel类型不匹配错误 Excel
【发布时间】:2018-07-29 17:30:13
【问题描述】:

我目前正在 excel 中运行 VBA 脚本,以允许特定用户名和密码访问特定工作表。我在 youtube 上关注本教程,一切似乎都很顺利,直到我开始遇到错误。

我的代码中出现类型不匹配错误,如下所示。有两行给我错误,他们评论,任何帮助将不胜感激!

Option Explicit

Sub CheckUser()
Dim UserRow, SheetCol As Long
Dim SheetNm As String
    With Sheet34
        .Calculate

        If .Range("B6").Value = Empty Then    'Incorrect Username
            MsgBox "Please enter a correct username"
            Exit Sub
        End If

        If .Range("B5").Value <> True Then    'Incorrect Password
            MsgBox "Please enter a correct password"
            Exit Sub
        End If

        UserForm1.Hide
        UserRow = .Range("b6").Value    'userrow

        .Range("B3").Value = ""
        .Range("b4").Value = ""

        For SheetCol = 6 To 26
            SheetNm = .Cells(2, SheetCol).Value    'SheetName

            If .Cells(UserRow, SheetCol).Value = "Ð" Then   ' line where error occurs
                Sheets(SheetNm).Protect "TEP2003"
                Sheets(SheetNm).Visible = xlSheetVisible
            End If

            If .Cells(UserRow, SheetCol).Value = "Ï" Then    ' line where error occurs
                Sheets(SheetNm).Visible = xlVeryHidden
            End If

        Next SheetCol
    End With
End Sub


Sub closeworkbook()
    Sheet1.Activate
    Dim WkSht As Worksheet
    For Each WkSht In ThisWorkbook.Worksheets
        If WkSht.Name <> "Main" Then WkSht.Visible = xlSheetVeryHidden
    Next WkSht
    ThisWorkbook.Save
End Sub

【问题讨论】:

  • 请考虑更好的格式。
  • 出错时UserRow、SheetCol的值是多少?你也可以 DIm UserRow As Long。它目前是隐含的变体。

标签: vba excel


【解决方案1】:

使用 Range.Text 属性。 Range.Text 不会修复工作表错误代码,但会将其评估为 Range.Value 将失败的文本。将两者与 ElseIf 结合起来;如果第一个通过,则评估第二个没有意义。

    ...
    If .Cells(UserRow, SheetCol).Text = "Ð" Then
    ...
    ElseIf .Cells(UserRow, SheetCol).Text = "I" Then
    ...
    End If

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多