Outlook 2007 Macro to read excel file containing file paths and create hyperlinks

◇◆丶佛笑我妖孽 提交于 2020-01-07 07:57:06

问题


I'm fairly new to VBA scripting and I'm trying to write a macro in Outlook that reads an excel file that has full paths and filenames in separate cells and inserts them as hyperlinks in an email. I've found information on how to create a hyperlink in Outlook but can't seem to find anything on how I would go about having Outlook actually getting the file paths from the Excel sheet. Any help or pointers in the right direction would be greatly appreciated. Thanks!

Edited to include a simple proof of concept that seems to be failing. Error says

Compile Error: User-defined type not defined

Here's what I have so far.

Sub links()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim FilePath As String

ExcelFileName = "C:\links.xlsx"
Set exWb = objExcel.Workbooks.Open(ExcelFileName)

FilePath = exWb.Sheets("Sheet1").Cells(1, 1)

oMsg.TextBody = Chr(34) & FilePath & Chr(34)


End Sub

回答1:


In the Outlook VBA editor set a reference to Excel.

Tools | References
Tick Microsoft Excel Object Library

Add Option Explict to new modules. You will find this helpful.

Tools | Options | Editor tab
Tick Require Variable Declaration

.

Option Explicit

Sub links()

Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim FilePath As String

Dim oMsg As mailItem

ExcelFileName = "C:\links.xlsx"

Set exWb = objExcel.Workbooks.Open(ExcelFileName)

FilePath = exWb.Sheets("Sheet1").Cells(1, 1)

On Error Resume Next
Set oMsg = ActiveInspector.currentItem
On Error GoTo 0
If oMsg Is Nothing Then
    Set oMsg = CreateItem(0)
    oMsg.Display
End If

' This adds to existing text. 
' Must display first to save a signature
'oMsg.body = Chr(34) & FilePath & Chr(34) & oMsg.body
'or
oMsg.HTMLBody = Chr(34) & FilePath & Chr(34) & oMsg.HTMLBody

ExitRoutine:
    Set oMsg = Nothing
    Set exWb = Nothing
    Set objExcel = Nothing

End Sub


来源:https://stackoverflow.com/questions/33743016/outlook-2007-macro-to-read-excel-file-containing-file-paths-and-create-hyperlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!