我有一个运行的Excel宏,它从电子表格中获取活动名称,日期和时间,并将它们放入Outlook日历中 . 这在Outlook运行时工作正常,但是当它不运行时,宏不会进行约会 .
我做了一个错误检查工件,检查是否正在运行的Outlook运行实例,如果没有运行,但它仍然只在Outlook运行时才有效 .
任何想法为什么??
Sub SetAppt()
' Dim olApp As Outlook.Application
Dim olApt As AppointmentItem
Dim olApp As Object
'if an instance of outlook is not open then create an instance of the application
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If er.Number = 429 Then
Set olApp = CreateObject("Outlook.Application.14")
End If
On Error GoTo 0
Set olApp = CreateObject("Outlook.Application")
' Set olApp = New Outlook.Application
'declare an index for all the variables
Dim i As Integer
i = 2
'declare the variables that will hold the data and set their initial value
Dim occ, actName, srtTime, duration As String
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
'for holding different parts of the dates/times that will be split
Dim splitStr() As String
Dim splitDrtion() As String
'loop until there is no more items
While Range(occ).Value <> ""
'create a new appointment
Set olApt = olApp.CreateItem(olAppointmentItem)
'we must split the start time and date
splitStr = Split(Range(srtTime).Value, " ")
Dim oDate As Date
oDate = splitStr(0)
'we must also spilt the duration (number/hour)
splitDrtion = Split(Range(duration).Value, " ")
'with is used to acces the appointment items properties
With olApt
.Start = oDate + TimeValue(splitStr(1))
'if the duration is in hours then multiply number else leave it
If splitDrtion(1) = "Hour" Then
.duration = 60 * splitDrtion(0)
Else
.duration = splitDrtion(0)
End If
.Subject = Range(occ).Value
.Body = Range(actName).Value
.Save
End With
'increment i and reset all the variables with the new number
i = i + 1
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
Set olApt = Nothing
Wend
Set olApp = Nothing
End Sub
2 回答
在Siddharth的示例基础上,这是您的代码的重构版本 .
此代码将工作表数据读入数组 . 这避免了VBA和Excel之间的COM交互带来的时间损失 .
我们遍历数组并为每一行创建一个新约会 .
使用以下示例数据,无论Outlook是否打开(Outlook被关闭使其明显变慢),它都能正常工作 .
事实上no need to check if Outlook is open .
代替
试试这个
由于我无法测试它,这里是您的代码与必要的更新 . 请试试这个 .