类型不匹配初始化变量时出错

时间:2014-05-02 12:05:53

标签: excel-vba runtime-error type-mismatch vba excel

我在excel VBA中出现了这个非常奇怪的错误,并且不断出现。我使用下面的代码

Public psword, oldpsword As Integer


Public Sub Auto_Open()

psword = Sheets("Main Menu").Cells(55, 1)
oldpsword = psword
For Each ws In Worksheets
    ws.Protect Password:=psword
Next ws

End Sub

每当代码进入第34行; oldpsword = psword"弹出一条错误消息,显示运行时' 13:'类型不匹配错误。我该如何解决?

2 个答案:

答案 0 :(得分:2)

尝试更换:

Public psword, oldpsword As Integer

Dim psword as Long, oldpsword as Long

答案 1 :(得分:0)

这里只是一个一般性的评论,因为simoco和Gary的学生已经让你系好了...如果你的密码可能是字母数字(这里有点远见可能会节省你将来的调试时间,特别是如果你的客户是得到密码错误哈哈),那么你可能想要使用variantCStrhttp://www.techonthenet.com/excel/formulas/cstr.php)的组合:

Public psword As Variant, oldpsword As Variant

Public Sub Auto_Open()

psword = ThisWorkbook.Sheets("Main Menu").Cells(55, 1)
oldpsword = psword
For Each ws In Worksheets
    ws.Protect Password:=CStr(psword)
Next ws

End Sub