how to use inlineshape addpicture function - vba

I wrote the code below to add an image to header. I placed the .png file in a network file. The following code works in my PC, but not in a different PC which also has access to the same network drive. It does import the image into the header but throws an error at the (.addpicture) line as shown in attached image. Wondering why the same code which works in one computer is bombing in the other one. Appreciate any directions. Thanks
Private Sub AddHeaderToRange(rng As Word.Range)
Dim sFindText As String
With rng
.Tables.Add Range:=rng, NumRows:=1, NumColumns:=2 'DefaultTableBehavior:=wdWord8TableBehavior,
AutoFitBehavior:=wdAutoFitFixed
With .Tables(1)
.PreferredWidth = Application.InchesToPoints(7)
.Rows.Alignment = wdAlignRowCenter
.Borders.InsideLineStyle = wdLineStyleNone
.Borders.OutsideLineStyle = wdLineStyleSingle
.Rows.SetLeftIndent LeftIndent:=0, RulerStyle:=wdAdjustNone
.Columns(1).SetWidth ColumnWidth:=200, RulerStyle:=wdAdjustNone
.Columns(2).SetWidth ColumnWidth:=225, RulerStyle:=wdAdjustNone
.cell(1, 1).Range.InlineShapes.AddPicture
Filename:="\\srv2\gv1\eng\strss\Pics\Testlogo.png", LinkToFile:=False,
SaveWithDocument:=True
.cell(1, 2).Range.Font.name = "Arial"
.cell(1, 2).Range.Font.Size = 12
.cell(1, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
.cell(1, 2).Range.Text = Sheets("Start").Range("P9").Value & " " &
Sheets("Start").Range("P10").Value
sFindText = Sheets("Start").Range("P9").Value & " " & Sheets("Start").Range("P10").Value
.cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
For Each r In .Rows
r.Borders(wdBorderLeft) = wdLineStyleNone
r.Borders(wdBorderRight) = wdLineStyleNone
r.Borders(wdBorderTop) = wdLineStyleNone
Next
.Rows(1).Cells.VerticalAlignment = wdAlignVerticalBottom
.AutoFitBehavior (wdAutoFitWindow)
'.Rows.WrapAroundText = True
End With
.ParagraphFormat.SpaceBefore = 0
.ParagraphFormat.SpaceAfter = 0
End With
With rng.Find
.Text = sFindText
If .Execute(Forward:=True) = True Then
rng.Fields.Add rng, _
wdFieldEmpty, _
"DocProperty TitleReference", PreserveFormatting:=True
End If
End With
Exit Sub
eh:
Call Errorhandler("AddHeaderToRange", Err)
End Sub

The syntax is:
Activedocument.Tables(1).Rows(1).Cells(1).Range.InlineShapes.AddPicture
After you fix that, you'll also get errors for the following lines that use .cell instead of Rows(1).Cells(1).

Related

Action on ContentControlCheckBox when checkbox is checked

I am trying to make a vba code in word to automating of insertion of tabels when a checkbox is cheked (True). But I get different type of error, deppending on whether I use the Boolean varable Checkbox1 or the ContentControl varable Checkbox1 in the IF statement, see the code below.
I have many of these checkboxes, in my document, så when the user click and chose one (or more) checkboxes the program shall insert a table for that specific checkbox.
Sub CheckBox_Click()
'Dim CheckBox1 As Boolean
Dim nytbl As Table
Dim CheckBox1 As ContentControl
Set CheckBox1 = Selection.Range.ContentControls.Add(wdContentControlCheckBox)
' CheckBox1.Checked = False
If (CheckBox1.Checked = True) Then
Set MyRange = ActiveDocument.Content
MyRange.Collapse Direction:=wdCollapseEnd
Set nytbl = ActiveDocument.Tables.Add(Range:=MyRange, NumRows:=3, NumColumns:=1)
nytbl.Select
nytbl.AutoFormat Format:=wdTableFormatList3
' formating of the table
With nytbl
.Cell(1, 1).Height = 30
.Cell(1, 1).Shading.BackgroundPatternColor = -738132173
.Cell(1, 1).Range.Font.Name = "Arial"
.Cell(1, 1).Range.Font.Size = 12
.Cell(1, 1).Range.Font.Bold = True
.Cell(1, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Cell(1, 1).Range.Font.TextColor = wdColorBlack
.Cell(1, 1).Range.InsertAfter " APPLIKATIONER "
.Cell(1, 1).VerticalAlignment = wdCellAlignVerticalCenter
.Cell(2, 1).Height = 30
.Cell(2, 1).Shading.BackgroundPatternColor = RGB(226, 239, 217)
.Cell(2, 1).Range.Font.Name = "Arial"
.Cell(2, 1).Range.Font.Size = 10
.Cell(2, 1).Range.Font.Bold = False
.Cell(2, 1).Range.Font.Italic = True
.Cell(2, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
.Cell(2, 1).Range.Font.TextColor = wdColorBlack
.Cell(2, 1).Range.InsertAfter " Applikationer kan indeholde data vedr. installerede applikationer. "
.Cell(2, 1).VerticalAlignment = wdCellAlignVerticalCenter
End With
End If
ActiveDocument.Paragraphs.Add 'insert new empty line
ActiveDocument.Paragraphs.Add 'insert new empty line
ActiveDocument.Paragraphs.Add 'insert new empty line
End Sub

VBA insert table in header

I want to insert 2 column and one row in header using vba. I tried the following code but it works one time and gives the error 6028 (the range cannot be deleted) other time. Can any one suggest me any solution.
Sub UpdateHeader()
Dim oDoc As Word.Document, oSec As Word.Section, rng As Word.Range
Set oDoc = ActiveDocument
For Each oSec In oDoc.Sections
Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
AddHeaderToRange rng
Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
AddHeaderToRange rng
Next oSec
End Sub
Private Sub AddHeaderToRange(rng As Word.Range)
With rng
.Tables.Add Range:=rng, NumRows:=1, NumColumns:=2
With .Tables(1)
.Borders.InsideLineStyle = wdLineStyleNone
.Borders.OutsideLineStyle = wdLineStyleNone
.Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
.Columns(2).SetWidth ColumnWidth:=300, RulerStyle:=wdAdjustNone
.Cell(1, 1).Range.InlineShapes.AddPicture FileName:="Your Pic Solution", LinkToFile:=False, SaveWithDocument:=True
.Cell(1, 2).Range.Font.Name = "Arial"
.Cell(1, 2).Range.Font.Size = 9
.Cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
.Cell(1, 2).Range.Text = "Test header" & vbNewLine & "Second Line"
End With
End With
End Sub
Try:
Sub UpdateHeaders()
Application.ScreenUpdating = False
Dim Tbl As Table, Sctn As Section
With ActiveDocument
Set Tbl = .Tables.Add(Range:=.Range(0, 0), NumRows:=1, NumColumns:=2)
With Tbl
.Borders.InsideLineStyle = wdLineStyleNone
.Borders.OutsideLineStyle = wdLineStyleNone
.Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
.Columns(2).SetWidth ColumnWidth:=300, RulerStyle:=wdAdjustNone
.Cell(1, 1).Range.InlineShapes.AddPicture FileName:="Your Pic Solution", LinkToFile:=False, SaveWithDocument:=True
.Cell(1, 2).Range.Font.Name = "Arial"
.Cell(1, 2).Range.Font.Size = 9
.Cell(1, 2).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
.Cell(1, 2).Range.Text = "Test header" & vbCr & "Second Line"
End With
For Each Sctn In .Sections
With Sctn
With .Headers(wdHeaderFooterPrimary)
If .LinkToPrevious = False Then .Range.FormattedText = Tbl.Range.FormattedText
End With
With .Headers(wdHeaderFooterFirstPage)
If .LinkToPrevious = False Then .Range.FormattedText = Tbl.Range.FormattedText
End With
End With
Next
Tbl.Delete
End With
Application.ScreenUpdating = True
End Sub

My Word macro doesn't find the second word

I want to create a VBA script in Microsoft Word to find inside a txt file if exist some line with ":" character. If this is true, I want to get this line, split it and insert this information in a table that is in main file. To this objetive, I want to go through all found lines to get this information.
For this, I have this code:
Dim arrNames
Dim cont As Integer
cont = 0
strPath = ActiveDocument.name
Documents.Open path & "Mails.txt"
strPath2 = ActiveDocument.name
With Selection.Find
.Text = ":"
Do While .Execute(Forward:=True, Format:=True) = True
Selection.Find.Execute FindText:=(":")
Selection.Expand wdLine
arrNames = Split(Selection.Text, ":")
Documents(strPath).Activate
If cont = 0 Then
Call gestOSINT("Pwd")
Selection.Find.Execute FindText:=("[Pwd]")
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:= _
3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
With Selection.Tables(1)
If .Style <> "Tabla con cuadrícula" Then
.Style = "Tabla con cuadrícula"
End If
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
.ApplyStyleRowBands = True
.ApplyStyleColumnBands = False
End With
Set tblNew = Selection.Tables(1)
tblNew.Style = "Tabla de lista 1 clara - Énfasis 1"
Selection.TypeText Text:="Correo electrónico"
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:="Tipo de filtrado"
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:="Plataforma"
End If
Set rowNew = tblNew.Rows.Add
rowNew.Cells(1).Range.Text = arrNames(0)
rowNew.Cells(2).Range.Text = arrNames(1)
rowNew.Cells(3).Range.Text = arrNames(2)
cont = cont + 1
Documents(strPath2).Activate
Selection.Text = arrNames(0) & vbCrLf
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.Collapse wdCollapseEnd
Loop
End With
Documents(strPath2).Activate
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Documents(strPath).Activate
If cont = 0 Then
pwdMails = False
Else
pwdMails = True
End If
And Mails.txt file contain the following:
mail#mail.com
mail2#mail.com
mail3#mail.com:word1:word2
mail4#mail.com
mail5#mail.com:word3:word4
The first line which contain ":", line 3 in Mails.txt, was found but the second line, line 5 in Mails.txt, wasn't found.
Why occur this? How can I fix it?
Here is a version that reads the file via FileSystemObject and avoids using Selection. PLease note that I commented out lines that do not work for me (style names, custom functions).
Also: you are applying two styles to the table, first one then the other. Please pick one. ;-)
Const ForReading = 1
Dim arrNames
Dim cont As Integer
Dim fso, MyFile, FileName, TextLine, tblNew As Table, newRow As Row
Set fso = CreateObject("Scripting.FileSystemObject")
cont = 0
If cont = 0 Then
'Call gestOSINT("Pwd")
'Selection.Find.Execute FindText:=("[Pwd]")
Set tblNew = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=1, NumColumns:= _
3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed)
With tblNew
' If .Style <> "Tabla con cuadrícula" Then
' .Style = "Tabla con cuadrícula"
' End If
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
.ApplyStyleRowBands = True
.ApplyStyleColumnBands = False
' .Style = "Tabla de lista 1 clara - Énfasis 1"
End With
With tblNew.Rows(1)
.Cells(1).Range.text = "Correo electrónico"
.Cells(2).Range.text = "Tipo de filtrado"
.Cells(3).Range.text = "Plataforma"
End With
End If
FileName = path & "Mails.txt"
Set MyFile = fso.OpenTextFile(FileName, ForReading)
Do While MyFile.AtEndOfStream <> True
TextLine = MyFile.ReadLine
If InStr(1, TextLine, ":") > 0 Then
arrNames = VBA.split(TextLine, ":")
Set rowNew = tblNew.Rows.Add
rowNew.Cells(1).Range.text = arrNames(0)
rowNew.Cells(2).Range.text = arrNames(1)
rowNew.Cells(3).Range.text = arrNames(2)
End If
Loop
MyFile.Close
If cont = 0 Then
pwdMails = False
Else
pwdMails = True
End If

Word-Vba: InlineShapes.Addpicture image sits higher than its previous image

Sub GetPictures()
Dim sPic As String
Dim sPath As String
Dim sCount As Long
sPath = "G:\Images\Alphabet_Lower_Case\"
sPic = Dir(sPath & "*.jpg")
Do While sPic <> ""
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
With Selection
With .Borders(wdBorderLeft)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderRight)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderTop)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderBottom)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
.Borders.Shadow = False
End With
Selection.Paragraphs.Format.Alignment = wdAlignParagraphCenter
sPic = Dir
With Selection
.Collapse Direction:=wdCollapseEnd
.TypeParagraph
End With
Loop
With ThisDocument.PageSetup.TextColumns
.SetCount NumColumns:=2
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Cut
End Sub
'Any idea on how to lower the image on the right hand side to the same level as the one of the left (previous)? E.g. b is sitting higher than it should be and is occluding the border.
All images have the same 600x600 dimension.
See the following output for clarification.
a&b
Here's a screen capture and the grid behind 'b' shows the shift.
preview

Formatting specific part of text string in VBA

I am in process of creating a macro that will save the current workbook, create a new outlook message and attach the file to the message. My macro does that but I can not format the text in the body of the email to my liking.
Dim OutApp As Object
Dim OutMail As Object
Dim sBody, Customer As String
ActiveWorkbook.Save
sBody = "All," & Chr(10) & Chr(10) & "Please Approve attached Request below for " & rType & "." _
& Chr(10) & Chr(10) & "Customer: " & customer & Chr(10)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = recip
.CC = CCed
.BCC = ""
.subject = subject
.Body = sBody
.Attachments.Add ActiveWorkbook.FullName
.display
End With
On Error GoTo 0
End Sub
I want the following message to be displayed (with the format) in the email.
All,
Please Approve attached Request below for "rtype".
Customer: Stackoverflow
So, the word "customer" needs to be bold. I have tired multiple solutions but they do not work as this is creating an outlook mail object.
Any Help will be appreciated.
**
Solution: To make the HTML tags work change the body type to html by
".HTMLBody". and you will be able to use HTML Tags. Kudos to Dick
Kusleika
**
HTML tags do work. I don't know why you say they don't.
sBody = "All,<br /><br />Please Approve attached request for " & rType & ".<br /><br /><strong>Customer:</strong> " & customer & "<br />"
then instead of the .Body property, use .HTMLBody
.HTMLBody = sBody
you have a few options
1)use HTML like a few people have commented
2)put that text on a hidden sheet and format it as required then ref it to the body as a range e.g. .Body = sheets("hidden_Body").range("A1:B10")
3)of you can try using something like below (please note below is used for adding one wingding character into a string and would need to be modified to fit your purpose)
Sub Build_Wingdings(Sh As Worksheet, rng As Range)
Dim cur_L As Integer
cur_L = 1
Sheets("Word_Specifications").Range("BZ9").Copy
Sh.Range(rng.Address).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
With Sheets("Word_Specifications")
.Select
For Each cell In .Range(.Range("Word_Standard_Start").Address, .Range("Word_Standard_Start").End(xlDown).Address)
If cell.value = "" Then
Else
L = Len(cell.value) + 1
With Sh.Range(rng.Address)
With .Characters(start:=cur_L, Length:=L).Font
.Name = "Arial"
.FontStyle = "Regular"
.Size = 9
.Bold = False
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
cur_L = cur_L + L
If .value <> "" Then
add_Wingdings cur_L, 1, Sh, rng
cur_L = cur_L + 2
End If
End With
End If
Next
End With
End Sub
Sub add_Wingdings(start As Integer, Length As Integer, Sh As Worksheet, rng As Range)
With Sh.Range(rng.Address).Characters(start:=start, Length:=Length).Font
.Name = "Wingdings 3"
.FontStyle = "Regular"
.Size = 9
.Bold = False
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
End Sub