vba 运行代码时获取用户定义类型未定义错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30598768/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting user-defined type not defined error when running code
提问by Kim G
Does anyone know why I'm getting a "user-defined type not defined" error in the Function GetOutlookApp() As Outlook.Applicationat the bottom of with this code?                              
有谁知道为什么我在Function GetOutlookApp() As Outlook.Application使用此代码的底部收到“未定义用户定义的类型”错误?                              
Sub CreateAppointments()
Dim cell As Excel.Range
Dim rng As Excel.Range
Dim wholeColumn As Excel.Range
Dim startingCell As Excel.Range
Dim oApp As Outlook.Application
Dim tsk As Outlook.TaskItem
Dim wkbk As Excel.Workbook
Dim wksht As Excel.Worksheet
Dim lastRow As Long
Dim arrData As Variant
Dim i As Long
' start Outlook app
' 启动 Outlook 应用程序
Set oApp = GetOutlookApp
If oApp Is Nothing Then
  MsgBox "Could not start Outlook.", vbInformation
  Exit Sub
End If
' get worksheet range into an array in one go
' 一次性将工作表范围放入数组中
Set wkbk = ActiveWorkbook
Set wksht = wkbk.ActiveSheet
Set wholeColumn = wksht.Range("B:B")
lastRow = wholeColumn.End(xlDown).Row - 2
Set startingCell = wksht.Range("B2")
Set rng = wksht.Range(startingCell, startingCell.Offset(lastRow, 1))
arrData = Application.Transpose(rng.Value)
' loop through array and create tasks for each record
' 遍历数组并为每条记录创建任务
For i = LBound(arrData, 2) To UBound(arrData, 2)
  Set tsk = oApp.CreateItem(olTaskItem)
  With tsk
    .DueDate = arrData(2, i)
    .Subject = arrData(1, i)
    .Save
  End With
Next I
End Sub
Function GetOutlookApp() As Outlook.Application
On Error Resume Next
Set GetOutlookApp = CreateObject("Outlook.Application")
End Function
回答by Eugene Astafiev
The How to automate Outlook from another programarticle describes all the required steps for automating Outlook. It states:
该如何从其他程序自动化Outlook本文介绍了自动运行Outlook的所有必要的步骤。它指出:
To use early binding, you first need to reference the available Outlook object library. To do this from Visual Basic (VB) or Visual Basic for Applications, follow these steps:
要使用早期绑定,您首先需要引用可用的 Outlook 对象库。要从 Visual Basic (VB) 或 Visual Basic for Applications 执行此操作,请执行以下步骤:
- In the Visual Basic Editor, on the Tools menu, click References.
- Click to select the Microsoft Outlook 15.0 Object Library check box, and then click OK.
- 在 Visual Basic 编辑器的工具菜单上,单击引用。
- 单击以选中 Microsoft Outlook 15.0 对象库复选框,然后单击确定。
回答by D. Chirita
I was have the same problem when I use Outlook in my scripts VBA Excel and I select:
我在脚本 VBA Excel 中使用 Outlook 时遇到了同样的问题,我选择了:
Tools > References > Check the checkbox in front of "Microsoft Outlook 15.0 Object Library.
工具 > 参考 > 选中“Microsoft Outlook 15.0 对象库”前面的复选框。

