Sub ForwardToExcel() Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Dim iLastRow As Integer Dim iRow As Integer Dim sSearch As String Dim sTo As String Dim objMail As Outlook.MailItem '获取当前邮件 Set objMail = Application.ActiveInspector.CurrentItem '打开Excel文件 Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Open("C:\MyExcel.xlsx") Set xlSheet = xlBook.Worksheets("Sheet1") '获取Excel表格最后一行 iLastRow = xlSheet.Cells(xlSheet.Rows.Count, "A").End(xlUp).Row '查找邮件内容在Excel中的行数 sSearch = objMail.Body For iRow = 1 To iLastRow If xlSheet.Cells(iRow, "A").Value = sSearch Then sTo = xlSheet.Cells(iRow, "B").Value Exit For End If Next iRow '将邮件转发到对应邮箱 If sTo <> "" Then Set objForward = objMail.Forward objForward.To = sTo objForward.Send End If '关闭Excel文件 xlBook.Close SaveChanges:=True xlApp.Quit Set xlSheet = Nothing Set xlBook = Nothing Set xlApp = Nothing Set objMail = Nothing End Sub 这个代码报错:运行时错误‘91’:对象变量或with块变量未设置,如何解决
时间: 2023-03-30 13:04:45 浏览: 199
vba-excel.zip_Excel VBA_VBa_excel_excel application _vba excel
这个问题可能是由于没有正确设置对象变量或with块变量引起的。您可以检查代码中是否有未设置的变量或对象,或者尝试使用“Set”语句为变量或对象分配值。您还可以尝试使用“On Error Resume Next”语句来避免出现运行时错误。
阅读全文