1

我一直在寻找几个小时试图找到如何修复我的代码,但问题是我不知道错误来自哪里!请帮忙!

我不断收到“运行时错误 13 类型不匹配”

Sub Mail_Every_Worksheet()

    Dim sh As Worksheet
    Dim wb As Workbook
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim OutApp As Object
    Dim OutMail As Object

    TempFilePath = Environ$("temp") & "\"

    If Val(Application.Version) < 12 Then
        FileExtStr = ".xlsm": FileFormatNum = 52
    End If

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set OutApp = CreateObject("Outlook.Application")

    For Each sh In ThisWorkbook.Worksheets
        If sh.Range("D9").Value Like "?*@?*.?*" Then

            sh.Copy
            Set wb = ActiveWorkbook

            TempFileName = "Sheet " & sh.Name & " of " _
                         & ThisWorkbook.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")

            Set OutMail = OutApp.CreateItem(0)

            With wb
                .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum

                On Error Resume Next
                With OutMail
                    .to = sh.Range("D9").Value
                    .CC = ""
                    .BCC = ""
                    .Subject = "WEEKLY BOOKING REPORT " & sh.Range("K3").Value
                    .Body = "Hi " & sh.Range("D8").Value & vbNewLine & "Please find attached our updated weekly booking report." & vbNewLine & "If I can be of further assistance please do not hesitate to contact me."
                    .Attachments.Add wb.FullName
                    .Display   'or use .Send
                End With
                On Error GoTo 0

                .Close savechanges:=False
            End With

            Set OutMail = Nothing

            Kill TempFilePath & TempFileName & FileExtStr

        End If
    Next sh

    Set OutApp = Nothing

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub
4

2 回答 2

2

在你的最后一条Dim语句之后(或整个Dim块之前),输入如下内容:

On Error Goto ErrHandler

然后在程序的底部(紧接在 之前End Sub),输入如下内容:

ErrHandler:
    If Err.Number <> 0 Then
        Stop 'DO NOT LEAVE THAT IN PRODUCTION CODE!!!
        Resume 'pressing F8 when "Stop" is highlighted will take you to the error line.
    End If

请注意,这严格来说是一个“调试”错误处理程序——如果您在生产中拥有这样的代码并遇到错误,则会启动 VBA IDE 并显示给您的用户进行调试。如果你离开Resume那里,你会有一个很好的无限循环。

此外,您On Error Goto 0将使错误处理程序无效,因此将其替换为On Error Goto ErrHandler.

于 2013-10-03T02:43:33.983 回答
1

我不确定它是否会这么简单:我认为 .xlsm 是在 excel 版本 12(2007)中引入的,但您的代码要求 Excel 版本小于 12(它没有 xlsm 文件类型)。将代码更改为“大于 11”是否有帮助?

If Val(Application.Version) > 11 Then
    FileExtStr = ".xlsm": FileFormatNum = 52
End If
于 2013-10-03T02:11:25.733 回答