Create One Calendar Event for Recordset range - vba

I'm trying to figure out how to add a loop that will only create one Outlook calendar event per Markdown End Date.
In my Table Pack Number 6772457 has a shared Markdown End Date date between all my Brand Offers of 2/9/2022 8AM. I'd like to find a way to create only one Entry for all these Brand Offers.
Logically, I'm having an issue figuring out how I would do a loop that would see Multiple Pack numbers on different dates and create event.
Note: The recordset could have multiple pack numbers with different dates and I want to try to make it so each pack number with a date gets a calendar event.
My current code is below.
Any thoughts or push in the right direction would be greatly appreciated!
Pack_Number
Brand Offer
Markdown End Date
6772457
W6
2/9/2022 8:00:00 AM
6772457
V6
2/9/2022 8:00:00 AM
6772457
S6
2/9/2022 8:00:00 AM
6772457
R6
2/9/2022 8:00:00 AM
6772457
P6
2/9/2022 8:00:00 AM
Private Sub Process_InSeason_Click()
Dim olobj As Outlook.Application
Dim oloappt As Outlook.AppointmentItem
Dim myOptionalAttendee As Outlook.Recipient
Dim PackNum As String
Dim rs As Dao.Recordset
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Define objects
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Appt = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Markdown End Date].Value
Appt = DateSerial(Year(Appt), Month(Appt), Day(Appt))
Appt = Appt + TimeSerial(8, 0, 0)
PackNum = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Pack_Number].Value
Set rs = CurrentDb.OpenRecordset("InS_tbl_Original")
Set olobj = CreateObject("Outlook.Application")
Set oloappt = olobj.CreateItem(olAppointmentItem)
Set myOptionalAttendee = oloappt.Recipients.Add("")
myOptionalAttendee.Type = olOptional
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Save records and turn on Error Control
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'DoCmd.RunCommand acCmdSaveRecord
On Error GoTo Add_Err
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Validate if Markdown End date is future date
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Markdown End Date").Value > Date Then
With oloappt
.RequiredAttendees = myOptionalAttendee
.Subject = "InSeason TEST" 'PackNum & " TEST"
'.Body =
.MeetingStatus = 1
.ResponseRequested = True
.Start = Appt
.Duration = 10
.ReminderSet = True
.ReminderMinutesBeforeStart = 1440
.Save
'.Display
.Send
.Close (olSave)
End With
DoCmd.RunCommand acCmdSaveRecord
MsgBox "Appointment Added!"
Else 'do nothing
End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'End process and clean up
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set oloappt = Nothing
Set olobj = Nothing
Exit Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Error validation
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Add_Err:
MsgBox "oops error found " & Err.Number & vbCrLf & Err.Description
Exit Sub
End Sub

I figured it out. In order to make this work I created a query off my table that will remove duplicate pack Numbers. From there I created a look through the records of the query. I want to leave this code active though for anyone who is trying to setup an outlook event through Access. Hopefully this helps!

Related

Create personal Calendar entry based on SharePoint Calendar entry

I'm trying to read my Sharepoint Calendar entries and then add one to my personal calendar with an offest of 4 hours on the same day.
The following creates a new entry but my For Each loop doesn't seem to work as it always jumps back to the main Function when I try to create a new Entry with the Date and Time read from the Variable "newStart".
Public newStart As String
Sub ReadEntries()
Dim oApp As Outlook.Application
On Error Resume Next
' check if Outlook is running
Set oApp = GetObject("Outlook.Application")
If Err <> 0 Then
'if not running, start it
Set oApp = CreateObject("Outlook.Application")
End If
Set olApp = New Outlook.Application
Set olFldr = olApp.GetNamespace("MAPI").Folders("Other Calendars").Folders("FOLDERNAME")
For Each Items In olFldr
If olFldr.Items.Subject = "Given Entry Title" Then
newStart = olFldr.Items.Start
CreateStandby
End If
Next
Set oObject = Nothing
Set oApp = Nothing
End Sub
Sub CreateStandby()
Dim standbyEntry As Object
Set standbyEntry = Application.CreateItem(olAppointmentItem)
standbyEntry.Subject = "New Entry Title"
standbyEntry.Start = newStart
standbyEntry.Duration = 240
standbyEntry.BusyStatus = olOutOfOffice
standbyEntry.Send
standbyEntry.Save
End Sub
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
' Avoid global variables unless there is no other way
' Inevitably the name will be non-unique
' You need something impossible to reproduce in other code
' Public newStart As String
Sub ReadEntries()
Dim olfldr As folder
Dim myItem As Object
' The less good version of GetObject was incorrectly done.
' Must return to regular error handling. On Error GoTo 0
'
' This shows the ideal, one line only, error bypass.
' https://stackoverflow.com/questions/22059917/how-to-verify-outlook-session-is-open-or-not-using-vba
'
' Unnecessary when code is in Outlook.
Set olfldr = Session.folders("Other Calendars").folders("FOLDERNAME")
For Each myItem In olfldr.Items
If myItem.Class = olAppointment Then
If myItem.subject = "Given Entry Title" Then
CreateStandby myItem.Start, myItem.Duration
End If
End If
Next
End Sub
Sub CreateStandby(itmStart As Date, itmDuration As Long)
Dim standbyEntry As AppointmentItem
Set standbyEntry = CreateItem(olAppointmentItem)
With standbyEntry
.subject = "New Entry Title"
' start 4 hours earlier
.Start = DateAdd("h", -4, itmStart)
' end at the same time
.Duration = itmDuration + 240
.Display
End With
End Sub

Create an Outlook reminder every two hours

I'm adding an Outlook reminder to run some code. I'd like it to run every two hours.
Below is a sample of one I have that runs every day at the same time. So today, when the Outlook reminder kicks off, it runs some code and then creates a new reminder for two hours from when this one ran.
For example, if this one runs at 7:30 AM, I'd like the new reminder to be created for 9:30 AM and then 11:30 AM, etc.
I'm struggling with the syntax on creating the next reminder. Part of my confusion is when the date changes.
Case "Move Files"
Move_FILES
Call New_Task("Move ENGIE Files", DateAdd("d", 1, Date), " 7:30:00 AM")
vAuto = True
I've used this code for a number of different processes and it has worked for a number of years. The only difference is now it needs to run every two hours.
Sub New_Task(vSubject As String, vDueDate As Date, vTime As String)
Dim myItem As Outlook.TaskItem
Set myItem = Application.CreateItem(olTaskItem)
With myItem
.Subject = vSubject
.DueDate = vDueDate
.ReminderTime = vDueDate & vTime
.Save
DoEvents
.ReminderSet = True
.Save
DoEvents
.ReminderSet = True
DoEvents
.Save
DoEvents
.Close (olSave)
DoEvents
End With
Set myItem = Nothing
End Sub
I was able to resolve my issue by adding a few lines at the beginning of the CASE statement. I added 2 variables and use them to figure out the date and time for the next reminder. Then I pass those 2 variables to the New_Task module. In case anyone wanted to see how I resolved my issue. Thanks...….
Case "Move ENGIE Files"
Dim MyTimer As String
Dim MyDate As Date
vTime = ""
MyTimer = ""
MyDate = 0
MyTimer = CDate(Now)
MyTimer = DateAdd("h", 2, MyTimer)
MyDate = Format(MyTimer, "MM/DD/YYYY")
MyTimer = Format(MyTimer, "HH:MM AM/PM")
MyTimer = " " & MyTimer
Move_Files
Call New_Task("Move ENGIE Files", MyDate, MyTimer)
vAuto = True

Ms-Access form data export to Word

I really some help! Here's a link to a google drive zip of the access database that I'm struggling with.
https://drive.google.com/file/d/0BwjnhQS2X7_Qamt4clFLc1Ztb2c/view?usp=sharing
So, what I have is an access database made up of a few tables and a form and some sub forms. The database info gets inputted to the tables via a form that I've created. In the example, the form is called "Database". This form exports to a word document, fields on the database go to bookmarks on the word doc. This works great so far.
In the attachment there is a "template" folder with the original word document, when the code runs it saves the completed form to the "generated" folder - works like a charm. Its a very long form for applications for liquor licenses.
So you fill in the form in access, it saves to the tables and exports the data to the word template document.
The problem that I have is that there is a subform on tab8 of the form where "director details" are saved. There can be any number of directors per application. I've managed to access the data on the subform's table, but have no idea how to loop through the data in that table to get all the information that is applicable to that application only and not data related to other applications. There is a relationship between the director details table and the application details table(this is the main table) and I'm using an application identifier field that I've created called and "ACNumber" which is unique to each application. There is a combobox on the form that selects the application and the form and subforms bring up the correct data when you select it.
The other part of the problem is how do I output this to word? A bookmark won't work, because all the fields are being repeated. Is there a way that all the data entries can be outputted to a single bookmark mabe in a textbox with the labels?
This is how it looks on the word document form:
(First person)
Full name : generate from item 5.4(a) from database
Physical address : generate from item 5.4(b) from database
Postal code : generate from item 5.4(c) from database
Postal address : generate from item 5.4(d) from database
Postal code : generate from item 5.4(e) from database
Identity number : generate from item 5.4(f) from database
(More person’s to add if needed)
Ok, I hope that describes my problem accurately.
I've tried all sorts to get this working, but its beyond me, please help guys!!!
Below is the code that I'm using: (the loop for the subform doesn't work, but one entry from that table is exported to the bookmarks currently in place)
I've tried all sorts to get this working, but its beyond me, please help guys!!!
`Private Sub ExportToWord_Click()
'Print customer slip for current customer.
Dim appWord As Word.Application
Dim doc As Word.Document
Dim drst As Recordset
Set drst = CurrentDb.OpenRecordset(Name:="62 Other Interests", Type:=RecordsetTypeEnum.dbOpenDynaset)
'Avoid error 429, when Word isnt open.
On Error Resume Next
Err.Clear
'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isnt open, create a new instance of Word.
Set appWord = New Word.Application
End If
Set doc = appWord.Documents.Open("C:\forms\templates\Form 3 - Sec 36(1).docx", , True)
With doc
.Bookmarks("wAppTradingNames").Range.Text = Nz(Me!AppTradingName, "")
.Bookmarks("wAppTradingName").Range.Text = Nz(Me!AppTradingName, "")
.Bookmarks("wCompanyName").Range.Text = Nz(Me!CompanyName, "")
.Bookmarks("wCompanyNumber").Range.Text = Nz(Me!CompanyNumber, "")
.Bookmarks("wRAddress1").Range.Text = Nz(Me!RAddress1, "")
.Bookmarks("wPostalCode").Range.Text = Nz(Me!PostalCode, "")
.Bookmarks("wRPostalAddress1").Range.Text = Nz(Me!RPostalAddress1, "")
.Bookmarks("wRPostalCode").Range.Text = Nz(Me!RPostalCode, "")
.Bookmarks("wDomicilium1").Range.Text = Nz(Me!Domicilium1, "")
.Bookmarks("wDomiciliumCode").Range.Text = Nz(Me!DomiciliumCode, "")
.Bookmarks("wDomAfter1").Range.Text = Nz(Me!DomAfter1, "")
.Bookmarks("wDomAfterCode").Range.Text = Nz(Me!DomAfterCode, "")
.Bookmarks("wTelOffice").Range.Text = Nz(Me!TelOffice, "")
.Bookmarks("wTelCell").Range.Text = Nz(Me!TelCell, "")
.Bookmarks("wTelHome").Range.Text = Nz(Me!TelHome, "")
.Bookmarks("wFaxNumber").Range.Text = Nz(Me!FaxNumber, "")
.Bookmarks("wEmail").Range.Text = Nz(Me!Email, "")
.Bookmarks("wFIP").Range.Text = Nz(Me!FIP, "")
.Bookmarks("wAppLicCat").Range.Text = Nz(Me!AppLicCat, "")
.Bookmarks("wLiqourType").Range.Text = Nz(Me!LiqourType, "")
.Bookmarks("wAppTradingName").Range.Text = Nz(Me!AppTradingName, "")
.Bookmarks("wAppTradingName").Range.Text = Nz(Me!AppTradingName, "")
.Bookmarks("wLPAddress").Range.Text = Nz(Me!LPAddress, "")
.Bookmarks("wErfNumber").Range.Text = Nz(Me!ErfNumber, "")
.Bookmarks("wLPPostalCode").Range.Text = Nz(Me!LPPostalCode, "")
.Bookmarks("wLPOwnership").Range.Text = Nz(Me!LPOwnership, "")
.Bookmarks("wLPOwnersName").Range.Text = Nz(Me!LpOwnersName, "")
.Bookmarks("wLpOwnerAddress").Range.Text = Nz(Me!LpOwnerAddress, "")
.Bookmarks("wLpRightOccupation").Range.Text = Nz(Me!LpRightOccupation, "")
.Bookmarks("wLPOccDuration").Range.Text = Nz(Me!LPOccDuration, "")
.Bookmarks("wLpPremNotErected").Range.Text = Nz(Me!LpPremNotErected, "")
.Bookmarks("wLpPremAlterReq").Range.Text = Nz(Me!LpPremAlterReq, "")
.Bookmarks("wLpPremAllGood").Range.Text = Nz(Me!LpPremAllGood, "")
.Bookmarks("wLpBuildCommence").Range.Text = Nz(Me!LpBuildCommence, "")
.Bookmarks("wLpBuildDuration").Range.Text = Nz(Me!LpBuildDuration, "")
.Bookmarks("wLpTradingHours").Range.Text = Nz(Me!LpTradingHours, "")
.Bookmarks("wLpRenewal").Range.Text = Nz(Me!LpRenewal, "")
.Bookmarks("wLpJobsa").Range.Text = Nz(Me!LpJobsa, "")
.Bookmarks("wLpJobsB").Range.Text = Nz(Me!LpJobsB, "")
.Bookmarks("wLpJobsC").Range.Text = Nz(Me!LpJobsC, "")
.Bookmarks("wNNPRegName").Range.Text = Nz(Me!NNPRegName, "")
.Bookmarks("wNNPRegNumber").Range.Text = Nz(Me!NNPRegNumber, "")
.Bookmarks("wNNPRegDate").Range.Text = Nz(Me!NNPRegDate, "")
.Bookmarks("wOtherInterests").Range.Text = Nz(drst!OtherInterests, "")
.Visible = True
.Activate
End With
Dim rst As Recordset: Set rst = CurrentDb.OpenRecordset(Name:="5 Director Details", Type:=RecordsetTypeEnum.dbOpenDynaset)
'Do While Not rst.EOF
With doc
.Bookmarks("wPersonLabel").Range.Text = Nz(rst!PersonLabel, "")
.Bookmarks("wFullName").Range.Text = Nz(rst!FullName, "")
.Bookmarks("wPhAddress").Range.Text = Nz(rst!PhAddress, "")
.Bookmarks("wPhCode").Range.Text = Nz(rst!PhCode, "")
.Bookmarks("wPAddress").Range.Text = Nz(rst!PAddress, "")
.Bookmarks("wPCode").Range.Text = Nz(rst!PCode, "")
.Bookmarks("wIdNumber").Range.Text = Nz(rst!IdNumber, "")
.Visible = True
.Activate
rst.MoveNext
End With
'Loop
doc.SaveAs2 "C:\forms\generated\" & Me!ACNumber & "_Form 3 - Sec 36(1).docx"
Set doc = Nothing
Set appWord = Nothing
Exit Sub
errHandler:
MsgBox Err.Number & ": " & Err.Description
End Sub
`
This will point you to the right direction. You need to make a couple of changes though to fit your needs e.g. insert all your bookmarks, update the SQL strings and recordset fields.
You also need to make a few changes to your Word document though:
1) Add a table to hold the manager data (loop). Hide the borders if needed.
2) Save the document as Word Template (.dotx)
Public Sub ExportToWord()
On Error GoTo ErrorTrap
Const TemplatePath As String = "C:\forms\templates\Form 3 - Sec 36(1).dotx"
'Data
Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT * FROM TableName WHERE [Criteria]", dbOpenSnapshot)
'SaveAs
Dim name_ As String
name_ = "C:\forms\generated\" & rs![FieldName] & "_Form 3 - Sec 36(1).docx"
'Word
Dim oWord As Word.Application
Set oWord = New Word.Application
oWord.Visible = False
Dim oDoc As Word.Document
Set oDoc = oWord.Documents.Add(TemplatePath)
With oDoc
.Bookmarks("Bookmark_1").Range.Text = rs![FieldName_1]
.Bookmarks("Bookmark_2").Range.Text = rs![FieldName_2]
.Bookmarks("Bookmark_3").Range.Text = rs![FieldName_3]
'...
End With
rs.Close
Set rs = Nothing
'Loop data
Set rs = CurrentDb().OpenRecordset("SELECT * FROM TableName WHERE [Criteria]", dbOpenSnapshot)
With rs
If Not .EOF Then
.MoveLast
.MoveFirst
End If
End With
Dim idx As Integer
For idx = 1 To rs.RecordCount
With oDoc.Tables(1)
.Cell(idx, 1).Range.Text = rs![FieldName_1] '1st Column
.Cell(idx, 2).Range.Text = rs![FieldName_2] '2nd Column
.Cell(idx, 3).Range.Text = rs![FieldName_1] '3rd Column
'...
'add extra rows if required
If rs.AbsolutePosition <> rs.RecordCount - 1 Then .Columns(1).Cells.Add
End With
rs.MoveNext
Next idx
'Save
With oDoc
.SaveAs FileName:=name_, FileFormat:=Word.WdSaveFormat.wdFormatXMLDocument
.Close SaveChanges:=wdDoNotSaveChanges
End With
Leave:
On Error Resume Next
rs.Close
Set rs = Nothing
oWord.Quit
Set oWord = Nothing
On Error GoTo 0
Exit Sub
ErrorTrap:
MsgBox Err.Description, vbCritical, "ExportToWord()"
Resume Leave
End Sub

Outlook VBA Mailitem property SenderEmailAddress not returning address correctly

So I have a program in access that lets the user select an outlook folder to import to a table. Which then can be selected from a combobox and transferred across to a form for use.
However I am having a problem with one of the values I am getting returned. SenderEmailAddress is not actually giving me an email address, for example this is what I get saved in my table.
I have removed names for privacy.
/O=COMPANY/OU=MAIL12/CN=RECIPIENTS/CN=FIRSTNAME.LASTNAME
Now of course, if I want to pass this value back over to outlook to reply to the email, I cannot use this.
Can anybody help me please?
Public Sub LoadEmails()
On Error Resume Next
'Outlook wasn't running, start it from code
If Started = False Then
Set olApp = New Outlook.Application '("Outlook.Application")
Started = True
End If
Set myNamespace = olApp.GetNamespace("MAPI")
Set objFolder = myNamespace.PickFolder
' if outlook is closed, it will display this error
If Err <> 0 Then
MsgBox "Outlook was closed. Please log out and log back in."
Started = False
Exit Sub
End If
'Exit if no folder picked.
If (objFolder Is Nothing) Then
MsgBox "No Folder Selected"
Started = False
Exit Sub
End If
Dim adoRS As Recordset
Dim intCounter As Integer
Set adoRS = CurrentDb.OpenRecordset("TBL_UserInbox") 'Open table Inbox
'Cycle through selected folder.
For intCounter = objFolder.Items.Count To 1 Step -1
With objFolder.Items(intCounter)
'Copy property value to corresponding fields
If .Class = olMail Then
adoRS.AddNew
adoRS("Subject") = .Subject
adoRS("TimeReceived") = .ReceivedTime
adoRS("Body") = .Body
adoRS("FromName") = .SenderEmailAddress '<<< Issue
adoRS("ToName") = .To
adoRS.Update
End If
End With
Next
MsgBox "Completed"
Started = False
End Sub
That is a perfectly valid email address of type EX (as opposed to SMTP). Check the MailItem.SenderEmailType property. If it is "SMTP", use the SenderEmailAddress property. If it is "EX", use MailItem.Sender.GetExchangeUser.PrimarySmtpAddress. Be prepared to handle nulls/exceptions.

MS Project 2007 VBA to retrieve tasks and custom fields

I have a simple MS Project file (2007) with just couple of tasks.
I have also created a custom field called VBATest and assigned values to this custom field against the two project tasks.
I would like to retrieve a list of project tasks and the value assigned to the custom field like this;
ProjectTask | VBATest <--Custom field
------------|--------
Task1 | vba1
Task2 | vba2
I'm doing this from Access 2007 VBA as this is where the final code will end up.
I can get most of it working, but I can't seem to read the custom field value from the Assignments object. Do you have Any ideas?
Thanks
Here is what I have done so far.
Sub LoadProjectFile()
Dim pjApp As MSProject.Application
Dim FileToOpen
Dim Proj As MSProject.Project
Dim Project_Task As Task
Dim fd As FileDialog
Set pjApp = New MSProject.Application
If pjApp Is Nothing Then
MsgBox "Project is not installed"
End
End If
pjApp.Visible = True
AppActivate "Microsoft Project"
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.Filters.Clear
fd.Filters.Add "Microsoft Project Files", "*.mpp"
fd.AllowMultiSelect = False
fd.Show
If (fd.SelectedItems.Count = 0) Then
'Application.GetOpenFilename("Microsoft Project Files (*.mpp), *.mpp")
pjApp.Quit
Set pjApp = Nothing
Exit Sub
End If
pjApp.FileOpen fd.SelectedItems(1)
Debug.Print "Project_Task_Name~CustomField"
Dim ass As Assignment
For Each Project_Task In pjApp.ActiveProject.Tasks
If Not Project_Task Is Nothing Then
For Each ass In Project_Task.Assignments
assignCFVal = assignCFVal & "," & ass.VBATestField '<<PROBLEM Line
Next ass
Debug.Print Project_Task.Name & "~" & assignCFVal
assignCFVal = ""
End If
Next Project_Task
pjApp.FileClose pjDoNotSave
pjApp.Quit
Set pjApp = Nothing
End Sub
It turns out I don't need to use the Assignments object for this. The SetField method would return what I need as below;
For Each Project_Task In pjApp.ActiveProject.Tasks
If Not Project_Task Is Nothing Then
assignCFVal = Project_Task.SetField(FieldNameToFieldConstant("VBATestField"))
Debug.Print Project_Task.Name & "~" & assignCFVal
End If
Next Project_Task