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 15:04:45 浏览: 103
这个问题可能是由于没有正确设置对象变量或with块变量引起的。您可以检查代码中是否有未设置的变量或对象,或者尝试使用“Set”语句为变量或对象分配值。您还可以尝试使用“On Error Resume Next”语句来避免出现运行时错误。
相关问题
VB6 打开Excel,程序容易闭退,请优化源代码:Function ReadMateria() As Boolean Dim xlRow As Integer, xlBook As New Excel.Workbook, xlSheet As New Excel.Worksheet, xlApp As New Excel.Application Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Open(ProcessPath.Text) Set xlSheet = xlBook.Worksheets("Material") For xlRow = 1 To 30 xlSheet.Cells(xlRow + 5, xlCol + 2) = "00" Next If Not xlBook Is Nothing Then xlBook.Close (True) Set xlBook = Nothing Set xlSheet = Nothing xlApp.Quit Set xlApp = Nothing End Function
以下是经过优化后的代码,可以避免程序崩溃:
Function ReadMateria() As Boolean
Dim xlBook As Excel.Workbook, xlSheet As Excel.Worksheet, xlApp As Excel.Application
On Error GoTo ErrHandler
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open(ProcessPath.Text)
Set xlSheet = xlBook.Worksheets("Material")
For xlRow = 1 To 30
xlSheet.Cells(xlRow + 5, xlCol + 2) = "00"
Next
xlBook.Close (True)
Set xlSheet = Nothing
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
ReadMateria = True
Exit Function
ErrHandler:
xlBook.Close (False)
Set xlSheet = Nothing
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
ReadMateria = False
End Function
主要优化措施包括:
1. 使用 Dim 声明变量时,只需要声明变量类型即可,不需要再使用 New 关键字。
2. 使用 On Error GoTo ErrHandler 语句,避免程序出现错误时直接崩溃。
3. 在 ErrHandler 中关闭 Excel 文件,并释放所有对象的引用。
4. 将函数的返回值设为 True 或 False,以便在程序中判断是否读取成功。
dsoframer.ocx怎么得到打开的excel的Application对象
要得到打开的Excel的Application对象,可以使用以下步骤:
1. 首先,需要确保已经引用了Excel对象库。在VB项目中,可以通过菜单栏中的“项目”->“引用”来添加。
2. 然后,在使用dsoframer.ocx打开Excel文档时,可以使用以下代码获取Excel的Application对象。
```vb
Dim xlApp As Excel.Application
Set xlApp = dsoframer1.Object.Application
```
其中,dsoframer1是使用dsoframer.ocx打开的Excel文档的对象名。
通过以上步骤,就可以得到打开的Excel的Application对象了。