Excel vba,使包含超链接的单元格出现在电子邮件正文中

添加提交date时,我有一个向用户发送电子邮件的代码。 在这封电子邮件的正文中,我指的是包含超链接到文件夹的单元格。 这个超链接的目的地出现,但它不活跃,这意味着它只出现在文本。 这里是我的代码,超链接单元格在电子邮件正文中引用

Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range ' The variable KeyCells contains the cells that will ' cause an alert when they are changed. Set KeyCells = Range("J3:J1000") If Not Application.Intersect(KeyCells, Range(Target.Address)) _ Is Nothing Then ' Display a message when one of the designated cells has been ' changed. ' Place your code here. Dim answer As String Dim SubmitLink As String SubmitLink = Target.Offset(, -8).Value answer = MsgBox("Do you wish to save this change. An Email will be sent to the User", vbYesNo, "Save the change") If answer = vbNo Then Cancel = True If answer = vbYes Then 'open outlook type stuff Set OutlookApp = CreateObject("Outlook.Application") Set OlObjects = OutlookApp.GetNamespace("MAPI") Set newmsg = OutlookApp.CreateItem(olMailItem) 'add recipients 'newmsg.Recipients.Add ("Name Here") newmsg.Recipients.Add Worksheets("Coordinator").Range("Q4").Value 'add subject newmsg.Subject = Worksheets("Coordinator").Range("O3").Value 'add body newmsg.Body = "Dear User, New Submittal ( " & SubmitLink & " ) has been Added in submittal Log. Please Investigate the Change" & vbLf & vbLf & vbLf & "Sincerely," newmsg.Display 'display newmsg.Send 'send message 'give conformation of sent message MsgBox "Modification confirmed", , "Confirmation" End If ' MsgBox "Cell " & Target.Address & " has changed." End If End Sub 

解释性图像

目前,您所创build的电子邮件是纯文本,因此基本上是接收电子邮件的客户端是否会自动尝试将看起来应该是超链接的东西变成实际的超链接。 格式为C:\Path\to\file.xls的文件path通常不适用。

这样做的正确方法是使用MailItem newmsgHTMLbody属性,并将您的信息parsing为HTML,指定究竟应该是超链接。

一个稍微“僵化”,但只使用纯文本这样做的一个相当简单的方法是稍微修改你的path。 如果您将file://附加到您的path中, 某些包括Outlook在内的电子邮件客户端将自动为您创build一个超链接。 所以,例如,你会改变你的newmsg.Body行来读取:

newmsg.Body = "Dear User, New Submittal ( file://" & SubmitLink & " ) has been Added in submittal Log. Please Investigate the Change" & vbLf & vbLf & vbLf & "Sincerely,"

这将产生一个超链接,如file://C:\Path\to\file.xls 。 显然,如果收件人使用的电子邮件客户端不会像我在这里描述的那样创build自动超链接,那么您将需要构build一个HTMLBody来使超链接正常工作。

编辑回应评论 ,简要说明如何使用HTMLBody 。 而不是设置newmsg.Body而是将newmsg.HTMLBody设置为HTML格式的消息。 用最简单的话来说,你可以按如下方式构build现有的消息。

  Dim emailBody As String ' At the very minimum your basic HTML page is made up of: ' <html> ' <body> ' Your message, including any formatting or hyperlniks. ' </body> ' </html> ' emailBody = "<html><body><font face=""Arial, sans-serif"">" emailBody = emailBody & "Dear User, New Submittal " emailBody = emailBody & "<a href=""" & SubmitLink & """>" & SubmitLink & "</a>" emailBody = emailBody & " has been Added in submittal Log. Please Investigate the Change<br><br><br>Sincerely," emailBody = emailBody & "</font></body></html>" newmsg.HTMLBody = emailBody 

如果你想进一步了解构buildHTML,我build议你看看W3Schools 。