受保护的Excel工作表复制到电子邮件错误

时间:2015-01-06 16:16:26

标签: vba email excel-vba outlook outlook-vba

我有一个受保护的工作表,我想使用宏将其复制到电子邮件中。我目前正在使用以下代码:

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

Sheets("Ordering").Select
Range("A1:H63").Select
Selection.Copy

With OutMail
    .To = ""
    .Cc = ""
    .BCC = ""
    .Subject = ""
    .Display
End With

SendKeys "^({v})", True

Set OutMail = Nothing
Set OutApp = Nothing

大部分时间都可以使用。但是,似乎有一个错误,即创建新电子邮件但未粘贴工作表。相反,Excel告诉我它不能这样做,因为工作表受到保护。

我尝试更改宏以便在选择之前取消保护并在粘贴后进行保护,但这只会导致新的电子邮件没有粘贴表单。

我尝试在protect命令之前添加一个wait命令,但这只会导致新的电子邮件没有粘贴工作表,并且宏需要更长时间才能结束。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

使用此代替SendKeys

OutMail.GetInspector().WordEditor.Range(1,1).Paste

全部放在一起,确保保护/取消保护工作表:

With Sheets("Ordering")
    .Unprotect
    .Range("A1:E12").Copy

    With OutMail
        .To = ""
        .Cc = ""
        .BCC = ""
        .Subject = ""
        .Display
        .GetInspector().WordEditor.Range(1,1).Paste
    End With

    .Protect
End With

答案 1 :(得分:1)

通常使用受保护的工作表时,有一点可能有用,就是使用VBA保护它们并指定UserInterFaceOnly:= True参数。这允许宏在受保护的工作表上执行大多数功能。但是,它只能由VBA完成,并且只在工作簿打开时持续存在,因此理想情况下它需要进入workbook_open事件模块。如果您要指定密码,那么密码保护您的vba模块也是一个好主意。保护例程的一些通用示例

For Each wsheet In ActiveWorkbook.Worksheets
    Select Case wsheet.Name
        Case "Some Specific Sheet Name 1", "Another Specific Sheet name"
            wsheet.Protect Password:=pw, DrawingObjects:=True, Contents:=True, Scenarios:=True, _
            AllowFiltering:=True, UserInterFaceOnly:=True
            wsheet.EnableSelection = xlNoRestrictions
        Case "Some Sheet I want to hide"
            wsheet.Protect Password:=pw, DrawingObjects:=True, Contents:=True, Scenarios:=True, _
            AllowFiltering:=True, UserInterFaceOnly:=True
            wsheet.EnableSelection = xlNoRestrictions
            wsheet.visible = False
        Case "LookupsSome Sheet I want to hide, but not protect"
            wsheet.visible = False
        Case "Some sheet I really really want to hide"
            wsheet.visible = xlVeryHidden
        Case "Some sheet I dont want to do anything with"
            'Dont do anything
        Case Else 'Every other sheet is hidden and protected
            wsheet.visible = False
            wsheet.Protect Password:=pw, DrawingObjects:=True, Contents:=True, Scenarios:=True, _
            AllowFiltering:=True, UserInterFaceOnly:=True
            wsheet.EnableSelection = xlNoRestrictions
    End Select
Next wsheet