Excel VBA单元格值与文本比较触发类型不匹配(错误13)问题排查
解决VBA运行时错误13(类型不匹配):Like运算符的类型问题
你遇到的运行时错误13(类型不匹配),直接原因是Like运算符要求操作数必须是字符串类型,但sh.Range("Q15").Value返回的不是字符串(比如单元格是空值、包含错误值#N/A/#VALUE!,或是数字、日期等非文本类型),导致类型不兼容。
核心修复思路
确保在使用Like之前,将单元格值转换为字符串,或者先校验值的类型,避免类型冲突。
具体修复方案
方案1:强制转换为字符串后再判断
将出错的语句修改为:
If CStr(sh.Range("Q15").Value) Like "?*@?*.?*" Then
CStr()函数会把单元格内容强制转为字符串,即使是空值、数字也能转为对应的字符串形式,彻底避免类型不匹配问题。
方案2:先校验值类型,再判断(更严谨)
如果需要跳过包含错误值的单元格,可以先做类型校验:
If Not IsError(sh.Range("Q15").Value) Then If TypeName(sh.Range("Q15").Value) = "String" Or IsNumeric(sh.Range("Q15").Value) Then If CStr(sh.Range("Q15").Value) Like "?*@?*.?*" Then ' 原有业务逻辑 End If End If End If
这个方案会先过滤错误值,再判断值是否能安全转为字符串,进一步降低异常概率。
修改后的完整代码
Sub Mail_Every_Worksheet_With_Address() 'Working only in 2007 and up Dim sh As Worksheet Dim TempFilePath As String Dim TempFileName As String Dim FileName As String Dim Mailbody As String 'Temporary path to save the PDF files TempFilePath = "C:\Users\Student\Downloads" 'Loop through every worksheet For Each sh In ThisWorkbook.Worksheets FileName = "" '修复:强制转换为字符串后判断邮箱格式,避免类型不匹配 If CStr(sh.Range("Q15").Value) Like "?*@?*.?*" Then 'If there is a mail address in Q15 create the file name and the PDF TempFileName = TempFilePath & sh.Range("C8").Value & " - " & Format(sh.Range("J8").Value, "yyyy.mm.dd") & ".pdf" TempFileName = Replace(TempFileName, ",", "") FileName = Create_PDF(Source:=sh, _ FixedFilePathName:=TempFileName, _ OverwriteIfFileExist:=True, _ OpenPDFAfterPublish:=False) 'If publishing is OK create the email If FileName <> "" Then With sh Mailbody = "<H3><B>" & .Range("Q17").Value & "</B></H3>" & _ .Range("Q18").Value & "<br>" & _ .Range("Q19").Value & "<br>" & _ .Range("Q20").Value & "<br>" & _ .Range("Q21").Value End With Mail_PDF_Outlook FileNamePDF:=FileName, _ StrTo:=sh.Range("Q15").Value, _ StrCC:="", _ StrBCC:="", _ StrSubject:=sh.Range("Q16").Value, _ Signature:=True, _ Send:=False, _ strbody:=Mailbody Else MsgBox "Not possible to create the PDF, possible reasons:" & vbNewLine & _ "Microsoft Add-in is not installed" & vbNewLine & _ "You Canceled the GetSaveAsFilename dialog" & vbNewLine & _ "The path to Save the file in arg 2 is not correct" & vbNewLine & _ "You didn't want to overwrite the existing PDF if it exist" End If End If Next sh End Sub
注:代码额外修复了With sh块内的Range引用,添加.前缀确保引用当前工作表的单元格,避免意外引用活动工作表。
额外检查点
- 检查所有工作表的Q15单元格:是否存在错误值(如#N/A、#VALUE!)、空值或非文本内容,这是触发问题的直接诱因。
- 原代码注释写的是"Test A1 for a mail address",但实际判断的是Q15,属于笔误,建议修正注释避免混淆。
内容的提问来源于stack exchange,提问作者Young student
相关产品推荐
相关产品推荐

