复制范围并作为outlook电子邮件正文发送

时间:2018-02-23 15:29:50

标签: excel vba

我有以下VBA代码来复制excel中的范围,并将其作为outlook的电子邮件正文发送。 excel表保存在服务器中,它在我的计算机和其他一些计算机/笔记本电脑上运行得非常好。但它给其他一些用户带来了编译错误。所有用户都连接到同一网络并使用相同版本的outlook和excel 2016.

  

编译错误 - 找不到项目或库

当我从同事(用户)的其他计算机上单击运行此脚本的命令按钮时,错误出现在(ERROR HERE)行中。 Outlook和Excel是2016年。我在参考菜单中添加了outlook对象库。 Excel工作表位于服务器文件夹\\hp-fs2\Groups\H&P ISM\Navigational Assessment上 任何修改本论坛专家代码的解决方案都将不胜感激。

Private Sub CommandButton1_Click()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Sheet1.Unprotect ("so")
Set rng = Nothing
On Error Resume Next
Set rng = Sheets("Sheet1").Range("B9:I22").SpecialCells(xlCellTypeVisible)
On Error GoTo 0

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

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

On Error Resume Next
With OutMail
    .To = "abcdg@abcd.com"
    .CC = ""
    .BCC = ""
    .Subject = "This is Automatic Notification - Navigation Assessment Overview sheet has just been updated !"
    .HTMLBody = RangetoHTML(rng)
    '.Send
    .display
End With
On Error GoTo 0

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

Set OutMail = Nothing
Set OutApp = Nothing

Sheet1.Protect ("so")
End Sub

Function RangetoHTML(rng As Range)

Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'( ERROR HERE - at the line TempFile = Environ$ )

rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

1 个答案:

答案 0 :(得分:0)

我对临时文件感兴趣...也许其他用户没有相应的凭据来保存到他们的计算机上的Environ $?或者Environ $指向一些受限制的网络位置?