VBA Access - Outlook cannot find name assigning a task through Access - ms-access

I have successfully written code to create a task in Outlook. I used the code below in Private Sub OutlookTask_Click() define the recipient and it worked fine as well. However, I needed to add some custom field in my Outlook Task form. I changed the code to what is listed in Private Sub test1_Click(). It works fine assigning the task to myself using .save. When I am assigning to someone else I get the error outlook cannot find the name. The answer posted worked fine, Just needed to change MyItem to OlTask.
Private Sub OutlookTask_Click()
Dim OlApp As Outlook.Application
Dim OlTask As Outlook.TaskItem
Dim OlTaskProp As Outlook.UserProperty
Dim OlLocation As Object
Dim OlDelegate As Outlook.Recipient
Dim TName As String
Set OlApp = CreateObject("Outlook.Application")
Set OlTask = OlApp.CreateItem(olTaskItem)
Set OlTaskProp = OlLocation.UserProperties.Find("Mlocation")
TName = Me.Alias
'Set OlDelegate = OlTask.Recipients.Add(TName)
With OLTask
.Subject = Me.Item
.StartDate = Me.Start_Date
.DueDate = Me.Due_Date
.Status = TStatus
.Importance = TPriority
.ReminderSet = True
.ReminderTime = Me.Due_Date - 3 & " 8:00AM"
.Body = Me.Description
.UserProperties("MLocation") = Me.Location
If Me.Alias = "Troy" Then
.Save
Else
.Assign
Dim myDelegate As Outlook.Recipient
Set myDelegate = OlTask.Recipients.Add(TName)
myDelegate.Resolve
End If
If myDelegate.Resolved Then
.Send
Else
MsgBox "Name not Found"
End If
MsgBox "Task Successful"
End Sub
Private Sub test1_Click()
Dim OlApp As Outlook.Application
Dim objFolder As MAPIFolder
Dim OLTask As Outlook.TaskItem
Dim OlItems As Outlook.Items
Dim OlDelegate As Outlook.Recipient
Dim TName As String
Dim TStatus As Integer
Dim TPriority As Integer
Set OlApp = CreateObject("Outlook.Application")
Set objFolder = OlApp.GetNamespace("MAPI").GetDefaultFolder(olFolderTasks)
Set OlItems = objFolder.Items
Set OLTask = OlItems.Add("IPM.Task.TroyTask")
TName = Me.Alias
Set OlDelegate = OLTask.Recipients.Add(TName)
With OLTask
.Subject = Me.Item
.StartDate = Me.Start_Date
.DueDate = Me.Due_Date
.Status = TStatus
.Importance = TPriority
.ReminderSet = True
.ReminderTime = Me.Due_Date - 3 & " 8:00AM"
.Body = Me.Description
.UserProperties("MLocation") = Me.Location
If Me.Alias = "Troy" Then
.Save
Else
.Assign
.Send
End If
End With
MsgBox "Task Successful"
End Sub

You seem to be submitting delegated task without sufficient preparation of its internal structures because Assign() is immediately followed by Send():
If Me.Alias = "Troy" Then
.Save
Else
.Assign
.Send ' problem
End If
In this case, recipients need to be resolved. See resolving of a task delegate's name visible in the working example. I adopted it without testing here:
If Me.Alias = "Troy" Then
.Save
Else
.Assign
Dim myDelegate As Outlook.Recipient 'added
Set myDelegate = OlTask.Recipients.Add(TName) 'added
myDelegate.Resolve 'added
If myDelegate.Resolved Then 'added
.Send
Else 'added
'report error here 'added
End If 'added
End If
The Resolve() call can be earlier in your code, this was just an illustration taken from the example.

Related

Column Headers to the last line of data entered to the HTMLBody

I've included the last line of data entered to my HTML body. However the column headers are not showing, what am I doing wrong?
Private Sub cmdEmail_Click()
'Declare Outlook Variables
Dim OLApp As Outlook.Application
Dim OLMail As Object
Dim MyData As Object
'Open the Outlook Application and Start a new mail
Set OLApp = New Outlook.Application
Set OLMail = OLApp.CreateItem(0)
Set MyData = ThisWorkbook.Worksheets("Database").Cells(Rows.count, 1).End(xlUp).Resize(, 13)
OLApp.Session.Logon
With OLMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Quality Alert"
.HTMLBody = "<P><font size='6' face='Calibri' color='black'>Quality Issue Found<br><br> Please reply back with what adjustments have been made to correct this issue. </font></P>" & ConvertRangeToHTMLTable(ThisWorkbook.Worksheets("Database").Cells(Rows.count, 1).End(xlUp).Resize(, 13))
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Database")
Dim wb As Workbook
ws.Copy
Set wb = ActiveWorkbook
wb.SaveAs "C:\Temp\Database.xlsx" 'Change Path
.Display
' .Send
wb.Close SaveChanges:=False
Kill "C:\Temp\Database.xlsx"
End With
'Clearing Memory
Set OLMail = Nothing
Set OLApp = Nothing
End Sub
Only the 1st 13 columns of the last row are being targeted.
ThisWorkbook.Worksheets("Database").Cells(Rows.count, 1).End(xlUp).Resize(, 13)
I order to include all the data, you'll have to extend the range from the first cell to the last row.
With ThisWorkbook.Worksheets("Database")
Set MyData = .Range(.Cells(1, 1), .Cells(Rows.Count, 1).End(xlUp).Resize(, 13))
End With
Breaking up the code into smaller bites will allow you to easily isolate and test your code.
Extracting the code that targets the data range into its own function (in a public module) allows use Application.Goto to visibly inspect the range.
Application.Goto EmailData
Private Sub cmdEmail_Click()
Dim HTMLBody As String
HTMLBody = EmailHTMLFirstAndLastRow
SendEmail HTMLBody
CreateACopyOfTheDatabaseSaveItCloseKillItButNeverDoAnythingWithit
End Sub
Place this code in a public module:
Sub SendEmail(HTMLBody As String)
'Declare Outlook Variables
Dim OLApp As Outlook.Application
Dim OLMail As Object
Dim MyData As Object
'Open the Outlook Application and Start a new mail
Set OLApp = New Outlook.Application
Set OLMail = OLApp.CreateItem(0)
OLApp.Session.Logon
With OLMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Quality Alert"
.HTMLBody = "<P><font size='6' face='Calibri' color='black'>Quality Issue Found<br><br> Please reply back with what adjustments have been made to correct this issue. </font></P>" & HTMLBody
.Display
' .Send
End With
'Clearing Memory
Set OLMail = Nothing
Set OLApp = Nothing
End Sub
Function EmailHTMLFirstAndLastRow() As String
Dim Target As Range
Set Target = EmailData
With Target
.EntireRow.Hidden = msoTrue
.Rows(1).Hidden = msoFalse
.Rows(.Rows.Count).Hidden = msoFalse
.EntireRow.Hidden = msoFalse
End With
EmailHTMLFirstAndLastRow = RangetoHTML(Target.Rows(Target.Rows.Count))
End Function
Function EmailData() As Range
With ThisWorkbook.Worksheets("Database")
Set EmailData = .Range(.Cells(1, 1), .Cells(Rows.Count, 1).End(xlUp).Resize(, 13))
End With
End Function
Sub CreateACopyOfTheDatabaseSaveItCloseKillItButNeverDoAnythingWithit()
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Database")
Dim wb As Workbook
ws.Copy
Set wb = ActiveWorkbook
wb.SaveAs "C:\Temp\Database.xlsx" 'Change Path
wb.Close SaveChanges:=False
Kill "C:\Temp\Database.xlsx"
End Sub
Edit
I edited the code to create html for only the header and last rows, as per the OP's request. Since RangetoHTML() ignores hidden rows, I define the range of data, hid all but the fist and last rows, the passed the range to RangetoHTML() and assigned its value to a variable, the unhid the range.

I can't read the Xml data by VBA(selectsinglenode but is nothing)

here is the Xml data
<NewZipCdListResponse>
<cmmMsgHeader>
<requestMsgId/>
<responseMsgId/>
<responseTime>20220526:085103847</responseTime>
<successYN>Y</successYN>
<returnCode>00</returnCode>
<errMsg/>
<totalCount>3</totalCount>
<countPerPage>1</countPerPage>
<totalPage>3</totalPage>
<currentPage>1</currentPage>
</cmmMsgHeader>
<newZipCdList>
<zipNo>11033</zipNo>
<address>경기도 연천군 전곡읍 은전로 80 (전곡리, 연천전곡새마을금고)</address>
<rangeKind/>
</newZipCdList>
</NewZipCdListResponse>
I wanna get it to my excel. But i don't know why I cannot do that.
maybe the error is in sentence, "set nodecell1 = objXml.select/.....".
Because nodecell have notthing and I don't know the reason.
here is part of my code.
Sub tracker()
Dim strURL As String
Dim strResult As String
Dim i As Long
Dim objHttp As New WinHttpRequest
Dim oldTime As Single
For i = 2 To Range("a60000").End(xlUp).Row
strURL = "http://openapi.epost.go.kr/postal/retrieveNewZipCdService/retrieveNewZipCdService/getNewZipCdList?ServiceKey=_____&srchwrd=" & Range("a" & i)
objHttp.Open "GET", strURL, False
objHttp.Send
If objHttp.Status = 200 Then '성공했을 경우(if success)
strResult = objHttp.ResponseText
'XML로 연결(contect XML)
Dim objXml As MSXML2.DOMDocument60
Set objXml = New DOMDocument60
objXml.LoadXML (strResult)
'노드 연결(contect node)
Dim nodeCell1 As IXMLDOMNode
Dim nodeCell2 As IXMLDOMNode
Set nodeCell1 = objXml.SelectSingleNode("/NewZipCdListResponse/newZipCdList/zipNo")
Set nodeCell2 = objXml.SelectSingleNode("/NewZipCdListResponse/newZipCdList/address")
'엑셀에 값 반영(input it to excel)
Cells(i, 2).Value = nodeCell1.Text
Cells(i, 3).Value = nodeCell2.Text
Else
End If
Next
End Sub
This works fine for me:
Sub tracker()
Dim objXml As MSXML2.DOMDocument60
Dim nodeCell1 As IXMLDOMNode
Dim nodeCell2 As IXMLDOMNode
Set objXml = New DOMDocument60
objXml.LoadXML Range("A1").Value 'loading XML from worksheet cell for testing
Set nodeCell1 = objXml.SelectSingleNode("/NewZipCdListResponse/newZipCdList/zipNo")
Set nodeCell2 = objXml.SelectSingleNode("/NewZipCdListResponse/newZipCdList/address")
Range("B1").Value = nodeCell1.Text
Range("C1").Value = nodeCell2.Text
End Sub
Output:

Reading htm file to .HTMLBody VBA

I'm attempting to automate an email using an Excel worksheet and VBA. I'm able to copy the desired range into the email, but I want to use a htm file for the HTML formatting.
How do I read a htm file and add it to the .HTMLBody of my email?
Here's my code, which sends an email with the correct worksheet, but does not include the HTML formatting that is added with the test(path) function:
Sub Send_To_Outlook()
Dim AWorksheet As Worksheet
Dim Sendrng As range
Dim rng As range
Dim text As String
Dim textline As String
Dim sPath As String
sPath = "H:\My Documents\email.htm"
On Error GoTo StopMacro
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Fill in the Worksheet/range you want to mail
Set Sendrng = Worksheets("Email").range("C6:L244")
'Remember the activesheet
Set AWorksheet = ActiveSheet
With Sendrng
' Select the worksheet with the range you want to send
.Parent.Select
'Remember the ActiveCell on that worksheet
Set rng = ActiveCell
'Select the range you want to mail
.Select
' Create the mail and send it
ActiveWorkbook.EnvelopeVisible = True
With .Parent.MailEnvelope
With .Item
.To = "myemail#email.com"
.CC = ""
.BCC = ""
.Subject = "My subject"
.HTMLBody = test(sPath)
.Send
End With
End With
'select the original ActiveCell
rng.Select
End With
'Activate the sheet that was active before you run the macro
AWorksheet.Select
StopMacro:
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
ActiveWorkbook.EnvelopeVisible = False
End Sub
Function test(sPath As String)
Dim oFSO As Object
Dim oFS As Object, sText As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFS = oFSO.OpenTextFile(sPath)
test= oFS.ReadAll()
End Function
Any suggestions or advice on why this isn't working would be awesome!
PS I also need to display the message instead of send, but this isn't as important of an issue.
Your function doesn't return any value.
Try this:
Function test(sPath As String)
test = CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath).ReadAll()
End Function
When you say that your code doesn't work, does that mean that you get an error or that the code executes but the email body is empty?
I would first check to see if your "test" Function is returning a null string:
Function test(sPath As String)
Dim oFSO As Object
Dim oFS As Object, sText As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFS = oFSO.OpenTextFile(sPath)
' I don't think you need to loop until EOF with .ReadAll
sText = oFS.ReadAll
' This will print sText to the Immediate Window; if it is 0, then sText is null
Debug.Print ("sText string has a length of: " & Len(sText))
End Function
My guess is that sText is null. If it is reading the .htm successfully, I would next check to make sure that the .htm is valid .html syntax.
I solved my problem. There was an issue when using html coupled with sending the worksheet range in the above code. I decided to covert the worksheet into html, export the chart into an image and insert it into the rest of the html for the email.
Sub Mail_Sheet_Outlook_Body()
Dim rng1 As range
Dim rng2 As range
Dim OutApp As Object
Dim OutMail As Object
Dim newimage As Action
Dim aPath As String
Dim bPath As String
Dim sPath As String
'Name the variables for your the needed paths
sPath = "C:\Chart1.png"
aPath = "C:\email1.htm"
bPath = "C:\email2.htm"
'Export your chart as an image
Call ExportChart("Chart1")
'Select the range your desired tables are in
Set rng1 = Worksheets("Email").range("C6:L32")
Set rng2 = Worksheets("Email").range("C45:L244")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'Create the email
On Error Resume Next
With OutMail
.To = "myemail#email.com"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
' Place your tables in the correct location of your html for the email
.HTMLBody = test(aPath) & RangetoHTML(rng1) & "<img src=" & "'" & sPath & "'" & "width=888; height=198>" & RangetoHTML(rng2) & test(bPath)
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function ExportChart(sChartName As String)
' Export a selected chart as a picture
Const sSlash$ = "/"
Const sPicType$ = ".png"
Dim sPath$
Dim sBook$
Dim objChart As ChartObject
On Error Resume Next
' Test if there are even any embedded charts on the activesheet
' If not, let the user know
Set objChart = ActiveSheet.ChartObjects(1)
If objChart Is Nothing Then
MsgBox "No charts have been detected on this sheet", 0
Exit Function
End If
' Test if there is a single chart selected
If ActiveChart Is Nothing Then
MsgBox "You must select a single chart for exporting ", 0
Exit Function
End If
Start:
' chart is exported as a picture, Chart1.png in the same
' folder location as the workbook
sBook = ActiveWorkbook.path
sPath = sBook & sSlash & sChartName & sPicType
ActiveChart.Export Filename:=sPath, FilterName:="PNG"
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
End Function
Function RangetoHTML(rng As range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Function test(sPath As String)
'Returns a string after reading the contents of a given file
test = CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath).ReadAll()
End Function
Thanks for all of your help! :)

Get the first line of text from email body with Outlook VB

I stole a function from somewhere online that allows me to take HTML from my clipboard and put in an Outlook 2013 email.
This works fine, but I would also like to modify it to grab the first line of text from the email body and use that as the subject line.
That way everything can be included in the HTML. However I have almost no experience with VB and after spending some time online look at API's and documentation I am still not able to figure it out. Here is what I have so far.
Sub PrependClipboardHTML()
Dim email As Outlook.MailItem
Dim cBoard As DataObject
Dim lines() As String
Set email = Application.ActiveInspector.CurrentItem
Set cBoard = New DataObject
cBoard.GetFromClipboard
email.HTMLBody = cBoard.GetText + email.HTMLBody
lines = Split(email.Body, vbNewLine)
' this does not produce anything
email.subject = lines(0)
'remove first line of email
Set cBoard = Nothing
Set email = Nothing
End Sub
To reiterate, I want to remove the first line of the post-formatted email body and use it as the subject line.
This is quick and dirty, grabbing a few mins here and there to construct, but something like this should get you started:
Public Sub PrependClipboardToHTML()
Dim email As Outlook.MailItem
Dim cBoard As DataObject
Dim cText, strLine As String
Dim strArray() As String
Set email = Application.CreateItem(olMailItem)
Set cBoard = New DataObject
cBoard.GetFromClipboard
cText = cBoard.GetText
strArray = Split(cText, vbCrLf)
strLine = CStr(strArray(0))
With email
.To = "someone#domain.com"
.Subject = strLine
.BodyFormat = olFormatHTML ' olFormatPlain == send plain text message
.HTMLBody = cText + email.HTMLBody
.Display
End With
Set email = Nothing
Set cBoard = Nothing
End Sub
I did some more research and read over the API's. In the end I figured it out. My solution is posted below. Thanks for all the help from the other commenters.
Sub PrependClipboardHTML()
Dim email As Outlook.MailItem
Dim cBoard As DataObject
Set email = Application.ActiveInspector.CurrentItem
Set cBoard = New DataObject
cBoard.GetFromClipboard
Dim sText As String
Dim headerStart As Integer
Dim headerEnd As Integer
Dim HTMLPre As String
Dim HTMLPost As String
Dim subject As String
Const headerStartLen = 20
Const headerEndStr = "</h2>"
sText = cBoard.GetText
headerStart = InStr(sText, "<h2 id=")
If headerStart > 0 Then
headerEnd = InStr(headerStart, sText, headerEndStr)
If headerEnd > 0 Then
subject = Mid(sText, _
headerStart + headerStartLen, _
headerEnd - headerStart - headerStartLen)
HTMLPre = Mid(sText, 1, headerStart - 1)
HTMLPost = Mid(sText, headerEnd + Len(headerEndStr))
End If
End If
email.HTMLBody = HTMLPre + HTMLPost + email.HTMLBody
If Len(email.subject) = 0 Then
email.subject = subject
End If
Set cBoard = Nothing
Set email = Nothing
End Sub

VBA code is getting error 462

I have the code below, in the OnClick event on a button that is located on a form. The code does the following:
In the sub form Forms! FrmFScomposition! PRODUCAO! [Prod_Cena_Guiao] (with an OLE object) I have a list of word documents, this list is updated with the help of a combobox. The code makes a Loop for all the documents and copies them to another sub form Forms! FrmFScomposition! SubfrmKitCenas! [FSKitCenasOLE], these documents are all in one. The code works fine, even if you repeat the process with the SAME data loaded. But when I choose another set of texts in the combobox, I get error 462, the first time I try the operation, but when I try again, the code works again. I'm tired of trying different possibilities, but I can not find a solution. Can someone help me or indicate something I'm missing? Below I will post the two subs that I am using. Thank you in advance for your attention.
code on button:
Private Sub Command54_Click()
Call DoResetKit
Dim FirstTime As Integer
FirstTime = 1
Me.FirstTimeBox = FirstTime
Forms!frmFScomposicao!PRODUCAO.SetFocus
DoCmd.RunCommand acCmdRecordsGoToFirst
For f = 1 To Forms!frmFScomposicao!PRODUCAO![tiroliro]
Call CompilarKitDiaGravacao
DoCmd.RunCommand acCmdRecordsGoToNext
Next f
DoCmd.RunCommand acCmdRecordsGoToFirst
End Sub
Code on first UDF
Public Sub CompilarKitDiaGravacao()
Dim CenasParaRecolha As Object
Dim DocumentoDestino As Object
Set CenasParaRecolha = Forms!frmFScomposicao!PRODUCAO![Prod_Cena_Guiao].Object.Application.WordBasic
Forms!frmFScomposicao!PRODUCAO![Prod_Cena_Guiao].Action = acOLEActivate
With CenasParaRecolha
Selection.WholeStory
Selection.Copy
End With
Set CenasParaRecolha = Nothing
If Forms!frmFScomposicao.FirstTimeBox = 1 Then
' Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Action = acOLEPaste
Set DocumentoDestino = Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Object.Application.WordBasic
Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Action = acOLEActivate
With DocumentoDestino
'Selection.WholeStory
'Selection.Delete
Selection.EndKey wdStory
Selection.InsertBreak Type:=wdSectionBreakContinuous
Selection.PasteAndFormat wdPasteDefault
End With
Set DocumentoDestino = Nothing
Forms!frmFScomposicao!FirstTimeBox = Forms!frmFScomposicao!FirstTimeBox + 1
Else
Set DocumentoDestino = Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Object.Application.WordBasic
Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Action = acOLEActivate
With DocumentoDestino
Selection.EndKey wdStory
Selection.InsertBreak 'Type:=wdSectionBreakContinuous
Selection.PasteAndFormat wdPasteDefault
End With
Set DocumentoDestino = Nothing
Forms!frmFScomposicao!FirstTimeBox = Forms!frmFScomposicao!FirstTimeBox + 1
End If
'Set CenasParaRecolha = Nothing
'Set DocumentoDestino = Nothing
End Sub
Code on second UDF
Public Sub DoResetKit()
Dim ResetKit As Object
Set ResetKit = Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Object.Application.WordBasic
Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Action = acOLEActivate
With ResetKit.Selection
Selection.WholeStory
Selection.Delete
End With
Set ResetKit = Nothing
End Sub
The working code for this is as follows:
Button Code:
Private Sub Command61_Click()
Dim ServerWordFS As Object
Set ServerWordFS = CreateObject("Word.Application")
Dim FirstTime As Integer
FirstTime = 1
For LoopCenasKit = 1 To Forms!frmFScomposicao!subfrmFScenas![tiroliro]
If FirstTime = 1 Then
Me.FirstTimeBox = FirstTime
Forms!frmFScomposicao!subfrmFScenas.SetFocus
Forms!frmFScomposicao!subfrmFScenas![EQUIPA].SetFocus
DoCmd.RunCommand acCmdRecordsGoToFirst
Call StartKit
DoCmd.RunCommand acCmdRecordsGoToNext
FirstTime = FirstTime + 1
Else
Call AddKit
DoCmd.RunCommand acCmdRecordsGoToNext
FirstTime = FirstTime + 1
End If
Next LoopCenasKit
ServerWordFS.Quit
End Sub
and two subs to create word doc wherever you want:
Public Sub StartKit()
Dim oAPP As Object
Dim oDoc As Word.Document
Dim cenaspararecolha As Object
Set oAPP = CreateObject(Class:="Word.Application")
With oAPP
.Visible = True
Set oDoc = .Documents.Add
oDoc.SaveAs "C:\Fserv\FolhaServiço", wdFormatDocument
End With
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].SetFocus
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Action = acOLEActivate
Set cenaspararecolha = Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Object.Application.WordBasic
With cenaspararecolha
Selection.WholeStory
Selection.Copy
End With
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Action = acOLEClose
With oAPP
.Selection.PasteSpecial DataType:=wdPasteRTF
End With
oDoc.Save
oDoc.Activate
oDoc.Close
oAPP.Quit
End Sub
Public Sub AddKit()
Dim oAPP As Object
Dim oDoc As Word.Document
Dim cenaspararecolha As Object
Set oAPP = CreateObject(Class:="Word.Application")
With oAPP
.Documents.Open Filename:="C:\Fserv\FolhaServiço.doc"
.Visible = True
.Selection.EndKey wdStory
.Selection.InsertBreak
End With
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].SetFocus
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Action = acOLEActivate
Set cenaspararecolha = Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Object.Application.WordBasic
With cenaspararecolha
Selection.WholeStory
Selection.Copy
End With
Forms!frmFScomposicao!subfrmFScenas![Prod_Cena_Guiao].Action = acOLEClose
With oAPP
.Selection.PasteSpecial DataType:=wdPasteRTF
Set oDoc = .ActiveDocument
oDoc.Save
End With
oDoc.Close
oAPP.Quit
End Sub