类型不匹配错误Excel

时间:2018-07-29 17:30:14

标签: excel vba excel-vba

我目前正在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

1 个答案:

答案 0 :(得分:0)

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

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