Specifying the location of an inlineshape in MS Word (VBA) - vb.net

I've been trying to adapt the method shown here: http://support.microsoft.com/kb/246299 so that I can create a command button in word which will save the document and remove itself when clicked. I've been unable to figure out how to change the position of the button from the default of the top left of the first page however. Ideally I'd like the button to be generated at the end of the document and be centre aligned, or otherwise placed at the cursor position.
Any advice would be very much appreciated :)
Thank You.
My VB.NET project code so far:
Dim shp As Word.InlineShape
shp = wrdDoc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
shp.OLEFormat.Object.Caption = "Save To Disk"
shp.Width = "100"
'Add a procedure for the click event of the inlineshape
Dim sCode As String
sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
"ActiveDocument.SaveAs(""" & sOutFile & """)" & vbCrLf & _
"On Error GoTo NoSave" & vbCrLf & _
"MsgBox ""Document Saved Successfully""" & vbCrLf & _
"Dim o As Object" & vbCrLf & _
"For Each o In ActiveDocument.InlineShapes" & vbCrLf & _
"If o.OLEFormat.Object.Name = ""CommandButton1"" Then" & vbCrLf & _
"o.Delete" & vbCrLf & _
"End If" & vbCrLf & _
"Next" & vbCrLf & _
"Exit Sub" & vbCrLf & _
"NoSave:" & vbCrLf & _
"MsgBox ""Document Failed To Save""" & vbCrLf & _
"End Sub"
wrdDoc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString(sCode)
wrdApp.Visible = True

As long as everything else is working just set the shp.left = 250 and shp.top = 1200
etc etc.
Just like in VB when you place a button. For more details on the exact calls you should reference this page: http://msdn.microsoft.com/en-us/library/office/hh965406%28v=office.14%29.aspx
But say to center a button you can set left to be the (doc.width - shape.width)
But word buttons allow for much more complex styling and setup.

Related

I cannot update a table field, error 3027(cannot update. Database object is read-only) keeps popping up

The email is able to be sent out but I keep receiving this error. This wasn't a problem before, the code worked fine and I was able to update a table field DateEmailSent but now that field can't be updated. This only happened after I created another form, could it be that the code in that form affected the code here.
Option Compare Database
Function GenerateEmail(MySQL As String)
On Error GoTo Exit_Function:
Dim oOutLook As Outlook.Application
Dim oEmailItem As Mailitem
Dim currentDate As Date
currentDate = Date
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset(MySQL)
'MsgBox rs.RecordCount
If rs.RecordCount > 0 Then
rs.MoveFirst
' MsgBox rs!Email
Do Until rs.EOF
If IsNull(rs!Email) Then
rs.MoveNext
Else
If oOutLook Is Nothing Then
Set oOutLook = New Outlook.Application
End If
Set oEmailItem = oOutLook.CreateItem(olMailitem)
With oEmailItem
.To = rs!Email
.CC = "josleasecollection#jos.com.sg"
.Subject = "End of Lease Product Collection Notification - " & rs!IDATender & " " & rs!PONumber & " CUSTOMER NAME: " & rs!AgencyName
.Body = "Dear Customer, " & vbCr & vbCr & _
"Notification of End of Lease Collection" & vbCr & _
"This is to inform you that leasing product(s) for PO #" & rs!PONumber & " will be expiring on " & rs!DueDate & vbCr & vbCr & _
"For a smooth and seamless collection process, you are required to: " & vbCr & _
" - To appoint a single contact point (Name, email and mobile contacts) for coordination purposes." & vbCr & _
" - To make verifications on the lease items for collection" & vbCr & _
" - To consolidate lease equipment & allocate holding are for onsite work purposes." & vbCr & _
" - To provide site clearance access if there are entry restrictions." & vbCr & _
" - To remove any additional parts (i.e. RAM, Additional HD, Graphic cards) installed in the lease equipment that is not part of the lease contract and BIOS password lock." & vbCr & _
" - To sign off all necessary asset & collection forms upon validations." & vbCr & vbCr & _
"Important Terms: " & vbCr & _
" 1. Lease equipment must be return in full and good working condition (with the exception of fair wear & tear)." & vbCr & _
" For Desktop, items to be collected with main unit as follows:" & vbCr & _
" - Power Adapter/Cable, Keyboard, Mouse" & vbCr & vbCr & _
" For Notebook, items to be collected with main unit as follows:" & vbCr & _
" - Power Adapter, Carrying case, Mouse" & vbCr & vbCr & _
" For Monitor, items to be collected with main unit as follows:" & vbCr & _
" - VGA Cable" & vbCr & vbCr & _
" 2. Any loss of lease equipment, you are required to immediately inform JOS and we will advise the relevant procedures." & vbCr & _
" 3. Collection must be completed no later than 14 days after the expiry of lease. We reserve the right to impose a late return fees (calculated on a daily basis) for any lease equipment." & vbCr & _
" 4. JOS will send in onsite engineers for asset verification and assist you. If onsite engineers are not available, JOS will provide a handbook for hard disk removal before collection, to which you shall immediately conduct the hard disk removal at your end." & vbCr & _
" 5. JOS shall not be held liable for any non-removal of any additional parts." & vbCr & _
" 6. JOS shall be indemnified in the event that collection is unsuccessful by the termination date due to the default or unreasonable delay caused by the customer. " & vbCr & _
" Appreciate for your acknowledgement by replying to josleasecollection#jos.com.sg by " & currentDate
.Send
rs.Edit
rs!dateemailsent = Date
rs.Update
End With
Set oEmailItem = Nothing
Set oOutLook = Nothing
rs.MoveNext
End If
Loop
Else
End If
This is the code for the new form i created.
Option Compare Database
Private Sub btnUpdateEmail_Click()
On Error GoTo Exit_UpdateEmail
Email_Update:
Dim db As DAO.Database
Dim qdf As QueryDef
Dim sql As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryUpdateEmail")
sqlString = "UPDATE Company SET Company.Email = '" & Me.txtNewEmail & "' WHERE Company.ContractNumber = '" & Me.txtContractNumber & "' "
qdf.sql = sqlString
If Nz(Me.txtContractNumber, "") = "" Then
MsgBox "Please enter a contract number"
Resume Exit_Update
ElseIf Nz(Me.txtNewEmail, "") = "" Then
MsgBox "Please enter a new email address"
Resume Exit_Update
End If
DoCmd.OpenQuery "qryUpdateEmail"
Exit_Update:
Exit Sub
Exit_UpdateEmail:
If Err.Number = 2501 Then
Resume Exit_Update
Else
MsgBox Err.Description
Resume Exit_Update
End If
End Sub
rs.Close
Exit_Function:
Exit Function
End Function

Microsoft.Office.Interop - ReplaceText (with) *NewLine* in Word.Table

I am having an application that uses Microsoft Word 2016 / the Interop interface to call the replace function. This way the application replaces some texts like 'Customername' to the actual name of the customer. Surely this is not the best way to do so, but thats how the application was build back in the days. Now I have to do some adjustments to the formatting facing a problem with the named function.
One of the Texts getting replaced is "[TELNR]" , beeing replaced with all known numbers of the customer, one number per line. Inserting New Lines as vbCr works great on a blank page as you can see top of the screenshot. The same called function will not put a new lines into a table (second page on the left) and won't even touch a textbox (second page on the right).
I have tried passing Line breaks as ^p, \n\r, \n, vbClRf / vbNewLine, vbCr. None of these will work.
I haven't found anything usefull on google or SO. Do you have ideas or a reason what might cause or even solve the problem?
#Region "Sample Strings"
Dim sample1 As String = "t:022220000000" & vbNewLine & "h:022221111111" & vbNewLine & ":0222222222222" & vbNewLine & "f:022223333333"
Dim sample2 As String = "t:022220000000" & vbCr & "h:022221111111" & vbCr & ":0222222222222" & vbCr & "f:022223333333"
Dim sample3 As String = "t:022220000000" & "^p" & "h:022221111111" & "^p" & ":0222222222222" & "^p" & "f:022223333333"
Dim sample4 As String = "t:022220000000" & "\n" & "h:022221111111" & "\n" & ":0222222222222" & "\n" & "f:022223333333"
Dim sample5 As String = "t:022220000000" & "\n\r" & "h:022221111111" & "\n\r" & ":0222222222222" & "\n\r" & "f:022223333333"
Dim sample6 As String = "t:022220000000" & vbCrLf & "h:022221111111" & vbCrLf & ":0222222222222" & vbCrLf & "f:022223333333"
#End Region
Private Sub replaceText(file As Microsoft.Office.Interop.Word.Document, find As String, replaceWith As String)
// First line was commented out for the ^p try
If replaceWith.Contains("^") Then replaceWith = replaceWith.Replace("^", "")
file.Content.Find.Execute(FindText:=find, ReplaceWith:=replaceWith, Replace:=Word.WdReplace.wdReplaceAll)
End Sub
The following was function was used to insert the textbox.

How to run a VBA macro every time text file is saved?

I am trying to find a way to run a macro every time a text file, any text file, in a certain folder is saved.
Does anyone know of a way to do that?
From: http://blogs.technet.com/b/heyscriptingguy/archive/2005/04/04/how-can-i-monitor-for-different-types-of-events-with-just-one-script.aspx
Sub Monitor()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\_Stuff""'")
Do While True
Set objEventObject = colMonitoredEvents.NextEvent()
Select Case objEventObject.Path_.Class
Case "__InstanceCreationEvent"
Debug.Print "A new file was just created: " & _
objEventObject.TargetInstance.PartComponent
Case "__InstanceDeletionEvent"
Debug.Print "A file was just deleted: " & _
objEventObject.TargetInstance.PartComponent
End Select
Loop
End Sub

vba add more than one space in vba email body?

I am using vba in outlook to generate an email. I would like to find a way to move some text over to the right, about 100 pixels.
since I don't believe there is a way to incorporate css or styles in vba I am looking for a way to add more than one space to get the text moved over. however when I try space() function and " ", even if I repeat these codes a number of times it only ever gives me one space.
can someone please help me and show me what I need to do, thanks
"<br><br><br>" & "3PL & HAULAGE SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount & "</b></font>" & vbNewLine & _
This will add 10 white spaces just before 3PL. You may need to adjust as the pixel distance will be relative to the font
TRIED AND TESTED
Sub test()
Dim WS As String
WS = "&nbsp"
For i = 1 To 10
WS = WS & "&nbsp"
Next i
Debug.Print "<br><br><br>" & WS & "3PL & HAULAGE SUPPLIERS: " & " " & "<font size=""4.5"" face=""calibri"" color=""red"">" & "<b>" & EmailCount & "</b></font>" & vbNewLine
End Sub

Error adding code to workbook via VBA

I am trying to use VBA in Excel to add conditional formatting to a column of a pivot table. The issue is that whenever the pivot table is refreshed, or a filter is changed, etc. the conditional formatting is lost. My solution was to add a macro to the pivot table update event in the workbook, which works ... kinda. It seems that when I run the code that creates the pivot table and adds the code to handle conditional formatting an error occurs but ONLY when the VBA window is NOT open. If the VBA window is open the code executes normally - despite no code changes or reference changes.
Private Sub setupConditionalFormattingForStatusColumn()
Dim thisSheetModule As vbcomponent
Dim formattingCodeString As String
On Error GoTo conditionalFormattingError
formattingCodeString = _
"Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)" & vbNewLine & _
" With Target.parent.Columns(" & harReportColumn("Status") & ")" & vbNewLine & _
" .FormatConditions.AddIconSetCondition" & vbNewLine & _
" .FormatConditions(.FormatConditions.Count).SetFirstPriority" & vbNewLine & _
vbNewLine & _
" With .FormatConditions(1)" & vbNewLine & _
" .IconSet = ActiveWorkbook.IconSets(xl4TrafficLights)" & vbNewLine & _
" .IconCriteria(1).Icon = xlIconYellowExclamation" & vbNewLine & _
vbNewLine & _
" With .IconCriteria(2) " & vbNewLine & _
" .Type = xlConditionValueNumber" & vbNewLine & _
" .value = -1" & vbNewLine & _
" .Operator = 5" & vbNewLine & _
" .Icon = xlIconGreenCircle" & vbNewLine & _
" End With" & vbNewLine & _
vbNewLine & _
" With .IconCriteria(3)" & vbNewLine & _
" .Type = xlConditionValueNumber" & vbNewLine & _
" .value = 1.05" & vbNewLine & _
" .Operator = 7" & vbNewLine & _
" .Icon = xlIconYellowCircle" & vbNewLine & _
" End With" & vbNewLine
formattingCodeString = formattingCodeString & vbNewLine & _
" With .IconCriteria(4)" & vbNewLine & _
" .Type = xlConditionValueNumber" & vbNewLine & _
" .value = 1.15" & vbNewLine & _
" .Operator = 7" & vbNewLine & _
" .Icon = xlIconRedCircleWithBorder" & vbNewLine & _
" End With" & vbNewLine & _
vbNewLine & _
" .ShowIconOnly = True" & vbNewLine & _
" End With" & vbNewLine & _
vbNewLine & _
" .HorizontalAlignment = xlCenter" & vbNewLine & _
" .VerticalAlignment = xlCenter" & vbNewLine & _
" End With" & vbNewLine & _
"End Sub"
Set thisSheetModule = ThisWorkbook.VBProject.VBComponents(harReportSheet.CodeName)
thisSheetModule.CodeModule.AddFromString formattingCodeString
Exit Sub
conditionalFormattingError:
errorLog.logError "WARNING: An error occured while applying the conditional formatting code for the ""Status"" column."
Err.Clear
Resume Next
End Sub
The line which generates the error is: thisSheetModule.CodeModule.AddFromString formattingCodeString but the error is only generated if the VBA window is closed.
Any ideas?
So I was able to find an answer to this issue. Evidently Excel does not properly initialize the codename property of newly created worksheets when the VBA window is not open (the why here is beyond me) but only when it recompiles. A work-around is to force Excel to recompile prior to any calls to the codename property. The solution which worked for me was to place the following code:
On Error Resume Next
Application.VBE.CommandBars.ActiveMenuBar.FindControl(ID:=578).Execute
On Error GoTo conditionalFormattingError
above the line beginning with Set thisSheetModule = ... . Oddly enough the line of code which forces the recompile also throws an error for me which I was able to safely ignore with the surrounding error handling.
More information can be found here: http://www.office-archive.com/2-excel/d334bf65aeafc392.htm
Hope that helps someone out there. :-)