Currently I am using this code which does not take in count the sparklines :
Sub generatemail()
Dim r As Range
Set r = Range("A1:F71")
r.Copy
Dim outlookApp As Outlook.Application
Set outlookApp = CreateObject("Outlook.Application")
Dim outMail As Outlook.MailItem
Set outMail = outlookApp.CreateItem(olMailItem)
outMail.Display
Dim wordDoc As Word.Document
Set wordDoc = outMail.GetInspector.WordEditor
wordDoc.Range.Paste
End Sub
The workaround I found to take in count spark line is to paste the image of the range with
wordDoc.Range.PasteAndFormat wdChartPicture
But they are blurred :
Does a way exist to copy sparkline ? (with Range.Copy) If it is not possible how would I get a better screen shot without blur ?
Note : When I do this by and the SparkLine are not blur :
I usually create a picture file then insert it on the mail. This works fine for me, try it.
Option Explicit
Private PicFilename As String
Sub generatemail()
Dim r As Range: Set r = Range("A1:F71")
' Create picture
Call createPicture("xChart", r)
Dim outlookApp As Outlook.Application: Set outlookApp = CreateObject("Outlook.Application")
Dim OutMail As Outlook.MailItem: Set OutMail = outlookApp.CreateItem(olMailItem)
' Display mail
OutMail.Display
' Insert picture
Dim shp As Word.InlineShape
Dim wordDoc As Word.Document: Set wordDoc = OutMail.GetInspector.WordEditor
Set shp = wordDoc.Range.InlineShapes.AddPicture(PicFilename)
End Sub
Public Function createPicture(picName As String, picRng As Range) As Boolean
Dim PicTop, PicLeft, PicWidth, PicHeight As Long
Dim oChart As ChartObject
createPicture = False
PicFilename = ThisWorkbook.Path & "\" & picName & ".jpg"
On Error Resume Next
Kill PicFilename
ActiveSheet.ChartObjects(1).Delete
On Error GoTo 0
On Error GoTo ErrHandler
' Delete any existing picture
On Error Resume Next
If Dir(PicFilename) > 0 Then Kill (PicFilename)
On Error GoTo 0
' Create a bitmap image
On Error Resume Next
picRng.CopyPicture xlScreen, xlBitmap
On Error GoTo 0
' Create a new Temporary Chart
PicTop = picRng.Top
PicLeft = picRng.Left
PicWidth = picRng.Width
PicHeight = picRng.Height
Set oChart = ActiveSheet.ChartObjects.Add(Left:=PicLeft, Top:=PicTop, Width:=PicWidth, Height:=PicHeight)
With oChart
.Name = picName
.Activate
' Select chart area
.Chart.Parent.Select
' Paste the Picture in the chart area
.Chart.Paste
' Save chart as picture
.Chart.Export PicFilename
' Delete Picture
.Delete
createPicture = True
End With
exitRoutine:
Exit Function
ErrHandler:
Debug.Print Now() & ": " & Err.Description
Resume exitRoutine
End Function
Related
I have a database in Excel, each entry runs horizontally for 8 cells (A2:H10 for example).
I am trying to create Word documents enmasse from each 8 cell entry that inject vertically into a Word document table that is 8 cells total.
Here is an example of the code I have tried.
Sub CreateEntry()
Dim wdApp As Object
Dim wd As Object
Dim myarray As Variant
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wd = wdApp.Documents.Add
wdApp.Visible = True
Sheets("Accommodation").Activate
Set Rng = ThisWorkbook.ActiveSheet.Range("A1:E76")
myarray = Range("A2:H2")
Range("A2:H2").Value = myarray
Range("A40:A48").Value = Application.WorksheetFunction.Transpose(myarray)
Set Rng = ThisWorkbook.ActiveSheet.Range("A40:A48")
Rng.Copy
With wd.Range
.Collapse Direction:=0
.InsertParagraphAfter
.Collapse Direction:=0
.PasteSpecial False, False, True
End With
End Sub
You can create tables directly in Word using the Word object model. That gives you more control over how it turns out.
Sub CreateEntry()
Dim doc As Object, rw As Range, tbl As Object
Dim n As Long
For Each rw In ThisWorkbook.Sheets("Accommodation").Range("A2:H3").Rows
Set doc = GetWordDoc()
Set tbl = doc.tables.Add(doc.Range, rw.Cells.Count, 1)
For n = 1 To rw.Cells.Count
tbl.Cell(n, 1).Range.Text = rw.Cells(n).Text
Next n
Next rw
End Sub
Function GetWordDoc() As Object
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
End If
On Error GoTo 0
Set GetWordDoc = wdApp.Documents.Add
End Function
I'm writing VBA program in powerpoint
The flow of program: VBA powerpoint macro have to open the excel file and copy and replace cell content to the specific shape in a specific slide.
Here the excel file has 21 columns. I have to copy and replace cell data to slide shape in slide #8. How to increment the cell value horizontally? Like a1 to b1 till 21 cells and repeat the same from beginning
here the code
Sub xltoppt()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\\Desktop\test.xls", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
Dim SheetName As String
Dim TestRange As Range
Dim TestSheet As Worksheet
Dim PasteRange As Boolean
Dim RangePasteType As String
Dim RangeName As String
Dim AddSlidesToEnd As Boolean
Dim shts As Worksheet
Dim sld As Slide
Dim grpItem As Shape
Dim shp As Shape
Dim i As Long
Dim j As Long
SheetName = ActiveSheet.Name
'Setting PasteRange to True means that Chart Option will not be used
PasteRange = True
RangeName = ("B1:B1") '"MyRange"
RangePasteType = "HTML"
RangeLink = True
PasteChart = False
PasteChartLink = True
ChartNumber = 1
AddSlidesToEnd = True
'Error testing
On Error Resume Next
Set TestSheet = Sheets(SheetName)
Set TestRange = Sheets(SheetName).Range(RangeName)
Set TestChart = Sheets(SheetName).ChartObjects(ChartNumber)
On Error GoTo 0
'If TestSheet Is Nothing Then
'MsgBox "Sheet " & SheetName & " does not exist. Macro will exit", vbCritical
Exit Sub
'End If
'If PasteRange And TestRange Is Nothing Then
MsgBox "Range " & RangeName & " does not exist. Macro will exit", vbCritical
Exit Sub
'End If
'Look for existing instance
'On Error Resume Next
'Set ppApp = GetObject(, "PowerPoint.Application")
'On Error GoTo 0
'Create new instance if no instance exists
''If ppApp Is Nothing Then Set ppApp = New PowerPoint.Application
'Add a presentation if none exists
'If ppApp.Presentations.Count = 0 Then ppApp.Presentations.Add
'Make the instance visible
ppApp.Visible = True
'Check that a slide exits, if it doesn't add 1 slide. Else use the last slide for the paste operation
For Each sld In ActivePresentation.Slides
For Each shp In sld.Shapes
If shp.HasTextFrame Then
If shp.TextFrame.HasText Then
shp.TextFrame.TextRange.Text = replace(shp.TextFrame.TextRange.Text, "happy", Worksheets(SheetName).Range(RangeName))
End If
End If
Next shp
Next
End Sub```
What I am trying to do.
I highlight some text in an email then run my macro.
It 'copies' the highlighted text and stores it in variable strText.
Then it creates a file called Artwork List.xlsx if it does not exist and if it exists it opens it.
After that it copies the text into the file in column A row 1 if the lastrow is 1, and if not, it appends to lastrow + 1
My code throws
'Run-time error 424, Object required'
To narrow down, the error should be coming from:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
or anything related to this line.
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object
Dim OutMail As Object
Dim olInsp As Object
Dim wdDoc As Object
Dim strText As String
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim strTextArr As Variant
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
FileName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & FileName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & FileName)
Set xlSheet = xlBook.Sheets(1)
Else
' Add Excel file
Set xlBook = xlApp.Workbooks.Add
With xlBook
.SaveAs FileName:="C:\Users\quaer\Desktop\DL Arts\" & FileName
End With
Set xlSheet = xlBook.Sheets(1)
End If
' Do stuff with Excel workbook
Dim i As Integer
Dim lastrow As Long
With xlApp
With xlBook
With xlSheet
strTextArr = Split(strText, "Adding file")
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastrow
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
.Close SaveChanges:=True
End With
End With
End With
xlApp.Visible = True
Exit Sub
End Sub
Try replacing this line, lastrow = .Cells(Rows.Count, 1).End(xlUp).Row, with:
lastrow = .Cells(1048576, 1).End(xlUp).Row
or
lastrow = .Cells(Rows.Count +1, 1).End(xlUp).Row
Jeeez this is crazy. I have found the problem finally and got a working code for anyone wanting similar usage. 1st off, I need to add the Microsoft excel add in. So in Outlook VBA, Tools -> references -> check Microsoft Excel 16.0 Object Library. This is to get rid of the 424 object required error, as I was trying to a call a excel built in method I guess. this is the line:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
Pls note that I am calling this macro from Outlook.
After this I faced a couple of other issues.
1. errors such as 424 run time, remote server machine does not exist or is not available.
first time running, it throws this error, 2nd time I click, the problem goes away. This is an issue with non specific use of the app, book and worksheet and so leaves VBA to assign on its own. Lesson learnt, be explicit about every thing.
leaves a copy of excel process even after program ends. This can be seen in task manager. This causes issues because then my excel file is linked to this process and not able to open without either read only or notify. Its locked with the process. So I cannot run again next time.
Anyway. Here is the final code. And I have also changed it to .Range instead of .Cells. I believe it does not matter if I used either but the key culprit is : xlSheet.Rows.Count. Instead of just Rows.Count, explicitly use xlSheet.Rows.Count.
Option Explicit
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object, OutMail As Object, olInsp As Object, wdDoc As Object
Dim xlApp As Excel.Application, xlBook As Excel.Workbook, xlSheet As Object
Dim strText As String
Dim strTextArr As Variant
Dim fName As String
Dim fileDoesExist As Boolean
Dim i As Integer
Dim lastrow As Long
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
'Close out all shit
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
On Error Resume Next 'Create or use a Excel Application
Set xlApp = GetObject(, "Excel.Application")
If Err.Number > 0 Then Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0
xlApp.Visible = False
xlApp.DisplayAlerts = False
fName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & fName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file if present
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & fName)
Else
' Add Excel file if not present
Set xlBook = xlApp.Workbooks.Add
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName
End If
Set xlSheet = xlBook.Worksheets(1)
' Do stuff with Excel workbook
strTextArr = Split(strText, "Adding file")
lastrow = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
xlBook.Close (True)
Set xlBook = Nothing
Set xlSheet = Nothing
xlApp.Visible = True
xlApp.Quit
Set xlApp = Nothing
MsgBox "Done!"
Exit Sub
End Sub
Thanks for the help and suggestions nonetheless.
I have an Excel file where when the user presses a button:
A range is selected and copied to the clipboard
An Outlook message is created based on a template
E-mail will be sent "on behalf of" instead of the user's name/account
The user adds a date in the e-mail and pastes the copied range into the template.
This is all working but Outlook adds the user's signature and that is unwanted.
Sub SelectArea()
Application.ScreenUpdating = False
lastCol = ActiveSheet.Range("a1").End(xlToRight).Column - 2
lastRow = ActiveSheet.Cells(500, lastCol).End(xlUp).Row
ActiveSheet.Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Copy
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItemFromTemplate("\\network\path\to\the\MailTemplate.oft")
With OutMail
.SentOnBehalfOfName = """DepartmentX"" <DepartmentX#company.com>"
.Display
End With
Application.ScreenUpdating = True
End Sub
Currently there is no DeleteSig sub. It used to be inside With OutMail. I tested the example from the Microsoft site 1:1 but could not get it to work.
The code from Microsoft:
Sub TestDeleteSig()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Set objOL = CreateObject("Outlook.Application")
Set objMsg = objOL.CreateItem(olMailItem)
objMsg.Display
Call DeleteSig(objMsg)
Set objMsg = Nothing
End Sub
Sub DeleteSig(msg As Outlook.MailItem)
Dim objDoc As Word.Document
Dim objBkm As Word.Bookmark
On Error Resume Next
Set objDoc = msg.GetInspector.WordEditor
Set objBkm = objDoc.Bookmarks("_MailAutoSig")
If Not objBkm Is Nothing Then
objBkm.Select
objDoc.Windows(1).Selection.Delete
End If
Set objDoc = Nothing
Set objBkm = Nothing
End Sub
It opens a new e-mail message with signature and gives a compile error.
"User-defined type not defined".
It marks Sub DeleteSig(msg As Outlook.MailItem) in yellow and highlights objDoc As Word.Document in blue.
This will remove the signature from an email template
The last Sub will place a selected range from Excel into the body of the template
Option Explicit
Public Sub TestDeleteSig()
Dim olApp As Object, olMsg As Object
Set olApp = CreateObject("Outlook.Application")
Set olMsg = olApp.CreateItem(0)
olMsg.Display
DeleteSig olMsg
InsertRng olMsg
Set olMsg = Nothing
End Sub
Private Sub DeleteSig(msg As Object)
Dim wrdDoc As Object, wrdBkm As Object
On Error Resume Next
Set wrdDoc = msg.GetInspector.WordEditor
Set wrdBkm = wrdDoc.Bookmarks("_MailAutoSig")
If Not wrdBkm Is Nothing Then wrdBkm.Range.Delete
Set wrdDoc = Nothing
Set wrdBkm = Nothing
End Sub
Private Sub InsertRng(msg As Object)
Dim rng As Range
Set rng = Selection.SpecialCells(xlCellTypeVisible)
If Not rng Is Nothing Then
If rng.Rows.Count = 1 And rng.Columns.Count = 1 Then
If Len(rng) = 0 Then Set rng = ActiveSheet.UsedRange.Cells(1)
End If
rng.Copy
msg.GetInspector.WordEditor.Content.PasteSpecial xlPasteAll
Application.CutCopyMode = False
End If
End Sub
If only one cell is selected and is empty, it will paste the first cell with data from ActiveSheet
So, this is the VBA code that is currently running.
It selects the range, copies it to a blank e-mail, pastes it there and deletes the users' signature.
The "problem" is that it should open a new e-mail based on an existing template (.oft) and paste it where it reads "<insert table/overview>". The oft has an image header and some (html/formatted) text in it.
I'm startin to wonder if what I'm trying to accomplish is even possible.
Sub DeleteSig()
Dim olApp As Object, olMsg As Object
Set olApp = CreateObject("Outlook.Application")
Set olMsg = olApp.CreateItemFromTemplate("\\myserver\my_template.oft")
olMsg.Display
DeleteSig_action olMsg
InsertRng olMsg
Set olMsg = Nothing
End Sub
Sub DeleteSig_action(msg As Object)
Dim wrdDoc As Object, wrdBkm As Object
On Error Resume Next
Set wrdDoc = msg.GetInspector.WordEditor
Set wrdBkm = wrdDoc.Bookmarks("_MailAutoSig")
If Not wrdBkm Is Nothing Then wrdBkm.Range.Delete
Set wrdDoc = Nothing
Set wrdBkm = Nothing
End Sub
Sub InsertRng(msg As Object)
Dim rng As Range
lastCol = ActiveSheet.Range("a1").End(xlToRight).Column - 2
lastRow = ActiveSheet.Cells(500, lastCol).End(xlUp).Row
Set rng = ActiveSheet.Range("a1", ActiveSheet.Cells(lastRow, lastCol))
rng.Copy
msg.GetInspector.WordEditor.Content.PasteSpecial xlPasteAll
Application.CutCopyMode = False
End Sub
Hers is the complete working code which removes signature from the mail template.
Option Explicit
Sub openEmail()
Dim cfgFromEmail As String
Dim cfgNotice As String
Dim cfgTemplate As String
Dim appOutlook As Outlook.Application
Dim newEmail As Outlook.MailItem
Dim rownum As Integer
Dim colnum As Integer
rownum = 6
cfgFromEmail = Sheets("Email").Range("O5").Value
cfgNotice = Sheets("Email").Cells(rownum, 10) '10 = column J
cfgTemplate = Sheets("Email").Cells(rownum, 11) '11 = column K
Set appOutlook = CreateObject("Outlook.Application")
Set newEmail = appOutlook.CreateItemFromTemplate(ThisWorkbook.Path & "\" & cfgTemplate & ".oft")
'Set template = mailApp.CreateItem(olMailItem) 'Creates a blank email
If cfgNotice <> "null" Then 'If is not blank
MsgBox cfgNotice, vbInformation, "Before you send the email"
End If
Dim objDoc As Word.Document
Dim objBkm As Word.Bookmark
On Error Resume Next
Set objDoc = newEmail.GetInspector.WordEditor
Set objBkm = objDoc.Bookmarks("_MailAutoSig")
If Not objBkm Is Nothing Then
objBkm.Select
objDoc.Windows(1).Selection.Delete
End If
Set objDoc = Nothing
Set objBkm = Nothing
With newEmail
.SentOnBehalfOfName = cfgFromEmail
.Display 'Show the email
End With
Set newEmail = Nothing
Set appOutlook = Nothing
End Sub
I have a word document which is updated periodically. I can go into that Word document, select the contents of an entire table and copy, then go into an Excel spreadsheet and paste it. It's screwed up; however, I fix it as follows:
sht.Cells.UnMerge
sht.Cells.ColumnWidth = 14
sht.Cells.RowHeight = 14
sht.Cells.Font.Size = 10
This manual copy-paste works regardless of whether the table is has merged fields.
Then I can start to manipulate it manually: parsing, checking, computations, etc.
I can do this one table at a time, but it's tedious and of course error prone.
I want to automate this. I found some code:
Sub read_word_document()
Dim sht As Worksheet
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
On Error GoTo ErrHandler
Set WordDoc = WordApp.Documents.Open("Z:\mydir\myfile1.DOC", ReadOnly:=True)
j = 0
For i = 1 To WordDoc.Tables.Count
DoEvents
Dim s As String
s = WordDoc.Tables(i).Cell(1, 1).Range.Text
Debug.Print i, s
WordDoc.Tables(i).
Set sht = Sheets("temp")
'sht.Cells.Clear
sht.Cells(1, 1).Select
sht.PasteSpecial (xlPasteAll)
End If
Next i
WordDoc.Close
WordApp.Quit
GoTo done
ErrClose:
On Error Resume Next
ErrHandler:
Debug.Print Err.Description
On Error GoTo 0
done:
End Sub
Of course this would just overwrite the same sheet again and again - and that's okay. This is just a test. The problem is this will work for those tables that do not have merged cells. However, it fails if the table has merged cells. I have no control over the file I get. It contains almost a hundred tables. Is there a way to do the copy paste the EXACT WAY that I do when I perform the operation manually?
Something like this:
Sub read_word_document()
Const DOC_PATH As String = "Z:\mydir\myfile1.DOC"
Dim sht As Worksheet
Dim WordDoc As Word.Document
Dim WordApp As Word.Application
Dim i As Long, r As Long, c As Long
Dim rng As Range, t As Word.Table
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
Set WordDoc = WordApp.Documents.Open(DOC_PATH, ReadOnly:=True)
Set sht = Sheets("Temp")
Set rng = sht.Range("A1")
sht.Activate
For Each t In WordDoc.Tables
t.Range.Copy
rng.Select
rng.Parent.PasteSpecial Format:="Text", Link:=False, _
DisplayAsIcon:=False
With rng.Resize(t.Rows.Count, t.Columns.Count)
.Cells.UnMerge
.Cells.ColumnWidth = 14
.Cells.RowHeight = 14
.Cells.Font.Size = 10
End With
Set rng = rng.Offset(t.Rows.Count + 2, 0)
Next t
WordDoc.Close
WordApp.Quit
End Sub