How to paste the whole range from Excel to Lotus as bitmap? - vba

I wrote a macro that works out quite well. I'm able to copy and paste given range (to be precise a pivot table) as bitmap but the problem is that not the whole are is copied, only a part of a table.
Here is the code, what's wrong with pasting? Why can't I copy the whole table?
Public Sub Lotus_Mail()
Dim NSession As Object
Dim NUIWorkSpace As Object
Dim NDatabase As Object
Dim NDoc As Object
Dim NUIdoc As Object
Dim Subject As String
Dim SendTo As String, CopyTo As String
Dim pivots As Range
Dim Month As String
Dim text1 As Range
Dim text2 As Range
Dim i As Integer
Dim arrHUBs(1 To 8) As String
arrHUBs(1) = "a"
arrHUBs(2) = "b"
arrHUBs(3) = "c"
arrHUBs(4) = "d"
arrHUBs(5) = "e"
arrHUBs(6) = "f"
arrHUBs(7) = "g"
arrHUBs(8) = "h"
Week = DatePart("ww", Date, vbMonday, vbFirstFourDays)
Month = MonthName(DatePart("m", Date), False)
On Error Resume Next
For x = 1 To 8
SendTo = Application.WorksheetFunction.VLookup(arrHUBs(x), Sheets("Mail").Range("A2:C9"), 2, 0)
CopyTo = Application.WorksheetFunction.VLookup(arrHUBs(x), Sheets("Mail").Range("A2:C9"), 3, 0)
Subject = "Summary " & arrHUBs(x) & " - " & Month & ": week " & Week
'area to select (pivot table)
rows = Sheets("sheet").Cells(Rows.Count, 21).End(xlUp).Row
columns = Sheets("sheet").Cells(6, Columns.Count).End(xlToLeft).Column
Set pivots = Sheets("sheet").Range(Cells(4, 19), Cells(wiersz, kolumna))
'Set pivots = Sheets("sheet").PivotTables("Pivot1") ???this line doesn't work, any other way to select pivot and paste to Lotus?
Set text1 = Sheets("Mail").Range("A12")
Set text2 = Sheets("Mail").Range("A13")
'Lotus step by step
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NDatabase = NSession.GetDatabase("", "")
If Not NDatabase.IsOpen Then NDatabase.OPENMAIL
'creating mail
Set NDoc = NDatabase.CreateDocument
With NDoc
.SendTo = SendTo
.CopyTo = CopyTo
.Subject = Subject
'Email body text, including a placeholder which will be replaced by Excel table
.body = text1 & vbLf & vbLf & _
"{IMAGE_PLACEHOLDER}" & vbLf
.Save True, False
End With
'Edit the new document using Notes UI to copy and paste pivot table into it
Set NUIdoc = NUIWorkSpace.EDITDocument(True, NDoc)
With NUIdoc
Sheets("sheet").Select
'Find the placeholder in the Body item
.GotoField ("Body")
.FINDSTRING "{IMAGE_PLACEHOLDER}"
'.DESELECTALL 'Uncomment to leave the placeholder in place (cells are inserted immediately before it)
'Copy pivot table (being a range) as a bitmap to the clipboard and paste into the email
pivots.CopyPicture xlBitmap
.Paste 'maybe any paste special option exists?
Application.CutCopyMode = False
'.Send
'.Close
End With
Set NSession = Nothing
Next x
End Sub
Thank you for your answers

Related

MS Word populate text after is inserted via VBA form

I have created word macro enabled template.
At opening form pops-up and user can fill in form. After pressing OK bookmarks inside document are updated and shown.
What I need is to populate entered values trough entire document on multiple locations. I have tried cross-referencing bookmarks but they are not updated with values entered in form.
image of opening form
Private Sub cancelBut_Click()
stInfo.Hide
End Sub
Private Sub Label11_Click()
End Sub
Private Sub OKbut_Click()
Dim katcest As Range
Set katcest = ActiveDocument.Bookmarks("katcest").Range
katcest.Text = Me.TextBox1.Value
Dim katopcina As Range
Set katopcina = ActiveDocument.Bookmarks("katopcina").Range
katopcina.Text = Me.TextBox2.Value
Dim zkcest As Range
Set zkcest = ActiveDocument.Bookmarks("zkcest").Range
zkcest.Text = Me.TextBox3.Value
Dim zkopcina As Range
Set zkopcina = ActiveDocument.Bookmarks("zkopcina").Range
zkopcina.Text = Me.TextBox4.Value
Dim zkulozak As Range
Set zkulozak = ActiveDocument.Bookmarks("zkulozak").Range
zkulozak.Text = Me.TextBox5.Value
Dim povrsina As Range
Set povrsina = ActiveDocument.Bookmarks("povrsina").Range
povrsina.Text = Me.TextBox6.Value
Dim vlasnik As Range
Set vlasnik = ActiveDocument.Bookmarks("vlasnik").Range
vlasnik.Text = Me.TextBox7.Value
Dim vladresa As Range
Set vladresa = ActiveDocument.Bookmarks("vladresa").Range
vladresa.Text = Me.TextBox8.Value
Dim datocevida As Range
Set datocevida = ActiveDocument.Bookmarks("datocevida").Range
datocevida.Text = Me.TextBox9.Value
Dim klasa As Range
Set klasa = ActiveDocument.Bookmarks("klasa").Range
klasa.Text = Me.TextBox10.Value
Dim urbroj As Range
Set urbroj = ActiveDocument.Bookmarks("urbroj").Range
urbroj.Text = Me.TextBox11.Value
Me.Repaint
Dim strDocName As String
Dim intPos As Integer
' Find position of extension in file name
strDocName = ""
intPos = InStrRev(strDocName, ".")
If intPos = 0 Then
' If the document has not yet been saved
' Ask the user to provide a file name
strDocName = InputBox("Upisi naziv " & _
"vaseg dokumenta.")
Else
' Strip off extension and add ".txt" extension
strDocName = Left(strDocName, intPos - 1)
strDocName = strDocName & ".docx"
End If
' Save file with new extension
ActiveDocument.SaveAs2 FileName:=strDocName, _
FileFormat:=wdFormatDocumentDefault
stInfo.Hide
infoForm.Show
End Sub

Paste not working between Excel and Word through VBA

I have a workbook which creates Word reports based on a Word template and tables in the workbook.
Depending on the equipment type, it copies a range from the spreadsheet and pastes it to two bookmark locations in the word document (bmInternal and bmExternal). I tried using PasteAppendTable, but this only works once. If I try to use it twice, for each bookmark, it copies nothing both times. As such I used Paste for one and PasteAppendTable for the second (PasteAppendTable is much neater as the formatting is better).
This worked fine, but I made changes to the code, not related to this, and now the Paste (which goes to bmInternal) isn't working. I can't see why when I've not changed anything regarding that part:
Sub Data2Word()
Application.GoTo Reference:=ActiveSheet.Range("A2")
GoAgain:
On Error Resume Next
Dim vItem As String
'Dim vImagePath As String
Dim vCurrentRow As Integer
Dim vDesc As String
Dim vN2 As String
Dim vGuide As String
Dim vUnit As String
Dim vBlock As String
Dim wrdPic As Word.InlineShape
Dim rng As Excel.Range 'our source range
Dim rngText As Variant
Dim rngText2 As Variant
Dim wdApp As New Word.Application 'a new instance of Word
Dim wdDoc As Word.Document 'our new Word template
Dim myWordFile As String 'path to Word template
Dim wsExcel As Worksheet
Dim tmpAut
'Find Item and type
vItem = ActiveCell.Value
vDesc = ActiveCell.Offset(0, 2)
vN2 = ActiveCell.Offset(0, 1)
vGuide = ActiveCell.Offset(0, 3)
vBlock = ActiveCell.Offset(0, 4)
vUnit = Left(vItem, 3)
If ActiveSheet.Range("rngREPORTED") = "Yes" Then
MsgBox vItem & " already has a report."
Exit Sub
End If
'initialize the Word template path
'here, it's set to be in the same directory as our source workbook
myWordFile = "W:\Entity\Inspect\WORD\INSPECTION TEMPLATES\Inspection Template - 20160511.dotx"
'open a new word document from the template
Set wdDoc = wdApp.Documents.Add(myWordFile)
If vGuide = "IGE01" Then
rngText = "rngEXCH"
rngText2 = "rngEXCHE"
ElseIf ActiveCell.Offset(, 4) = "Mono" Then
'Do Mono
rngText = "rngMONO"
Else
ActiveWorkbook.Names.Add Name:="rngItemSub", RefersTo:=Worksheets("SubEquipment").Range("B" & ActiveCell.Offset(0, 6) & ":C" & ActiveCell.Offset(0, 7) + ActiveCell.Offset(0, 6))
CarryOn:
rngText = "rngItemSub"
End If
'Insert Tables
'get the range of the data
Set rng = Range(rngText)
rng.Copy 'copy the range
wdDoc.Bookmarks("bmInternal").Range.Paste 'AppendTable
If vGuide = "IGE01" Then
Set rng = Range(rngText2)
rng.Copy
End If
wdDoc.Bookmarks("bmExternal").Range.PasteAppendTable
wdDoc.Bookmarks("bmItem").Range.InsertAfter vItem
wdDoc.Bookmarks("bmDesc").Range.InsertAfter vDesc
wdDoc.Bookmarks("bmN2").Range.InsertAfter vN2
wdDoc.Bookmarks("bmGuide").Range.InsertAfter vGuide
wdDoc.Bookmarks("bmBlock").Range.InsertAfter vBlock
wdDoc.Variables("wvItem").Value = vItem
ActiveDocument.Fields.Update
With wdDoc
Set wrdPic = .Bookmarks("bmImage").Range.InlineShapes.AddOLEObject(ClassType:="AcroExch.Document.7", Filename:="W:\Entity\Inspect\T&I\2016\Various Items\Photos\Sorted\" & vItem & ".pdf", LinkToFile:=False, DisplayAsIcon:=False)
wrdPic.ScaleHeight = 55
wrdPic.ScaleWidth = 55
End With
wdApp.Visible = True
wdApp.Activate
wdDoc.SaveAs "W:\Entity\Inspect\WSDATA\REPORTS\2016\" & vUnit & "\" & vItem & " " & vN2 & " THO.docx" 'Mid(ActiveDocument.Name, 1, Len(ActiveDocument.Name) - 4)
MoveHere:
ActiveWorkbook.Sheets("AllItems").Range("G" & ActiveCell.Offset(0, 8)).Value = "Yes"
ActiveWorkbook.Save
End Sub
I think DocVariables are easier to use that Bookmarks. Do a quick Google search on Word DocVariables. Get things setup correct in Word, and then run the script below.
Sub PushToWord()
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next
objWord.ActiveDocument.variables("FirstName").Value = Range("FirstName").Value
objWord.ActiveDocument.variables("LastName").Value = Range("LastName").Value
objWord.ActiveDocument.variables("AnotherVariable").Value = Range("AnotherVariable").Value
objWord.ActiveDocument.Fields.Update
'On Error Resume Next
objWord.Visible = True
End Sub

Script to run a macro at a specific time with excel running in invisible mode

'This code is inside an module of a Workbook.
Sub Notes_Email_Excel_Cells2()
Application.WindowState = xlNormal
Dim NSession As Object
Dim NDatabase As Object
Dim NUIWorkSpace As Object
Dim NDoc As Object
Dim NUIdoc As Object
Dim WordApp As Object
Dim subject As String
Dim dd As String
Dim stAttachment As String
Dim obAttachment As Object, EmbedObject As Object
Const EMBED_ATTACHMENT As Long = 1454
Dim Wb As Workbook
Dim FirstCell As Range, LastCell As Range
Dim CC(1)
CC(1) = "yyy#itc.in,"
If bIsBookOpen("Daily Beetle Count Report - MMGR.xlsx") = True Then
Set Wb = Workbooks("Daily Beetle Count Report - MMGR.xlsx")
Else
Workbooks.Open ("B:\Sangeet\Daily Beetle Count Report - MMGR.xlsx")
Set Wb = Workbooks("Daily Beetle Count Report - MMGR.xlsx")
End If
Set NSession = CreateObject("Notes.NotesSession")
'Next line only works with 5.x and above. Replace password with your password
subject = "HOT SPOTS Infestation " & Now
Debug.Print subject
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NDatabase = NSession.GetDatabase("", "")
If Not NDatabase.IsOpen Then NDatabase.OPENMAIL
'Create a new Lotus Notes document
Set NDoc = NDatabase.CreateDocument
stAttachment = ActiveWorkbook.FullName
Set obAttachment = NDoc.CreateRichTextItem("stAttachment")
Set EmbedObject = obAttachment.EmbedObject(EMBED_ATTACHMENT, "", stAttachment)
With NDoc
.SendTo = "xxx#itc.in" 'CHANGE RECIPIENT EMAIL ADDRESS
.CopyTo = ""
.subject = subject
'Email body text, including marker text which will be replaced by the Excel cells
.body = "Dear All," & vbLf & vbLf & "Please find the Hotspot areas" & vbLf & vbLf & _
"**PASTE HERE**" & vbLf & vbLf & vbLf & vbLf & _
"Auto Generated Mail. Please Donot Reply."
.Save True, False
End With
'Edit the just-created document to copy and paste the Excel cells into it via Word
Set NUIdoc = NUIWorkSpace.EDITDocument(True, NDoc)
With NUIdoc
'Find the marker text in the Body item
.GotoField ("Body")
.FINDSTRING "**PASTE HERE**"
'.DESELECTALL 'Uncomment to leave the marker text in place (cells are inserted immediately before)
'Copy Excel cells to clipboard
Wb.Sheets("HOT SPOT").Activate
Sheets("HOT SPOT").Range("v2:w21").Copy 'CHANGE SHEET AND RANGE TO BE COPIED AND PASTED
'Create a temporary Word Document
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False 'True to aid debugging
WordApp.Documents.Add
'Paste into Word document and copy to clipboard
With WordApp.Selection
.PasteSpecial DataType:=10 'Enum WdPasteDataType: 10 = HTML; 2 = Text; 1 = RTF
.WholeStory
.Copy
End With
'Paste from clipboard (Word) to Lotus Notes document
.Paste
Application.CutCopyMode = False
WordApp.Quit SaveChanges:=False
Set WordApp = Nothing
.Send
.Close
End With
Set NSession = Nothing
If bIsBookOpen("Daily Beetle Count Report - MMGR.xlsx") Then
Workbooks("Daily Beetle Count Report - MMGR.xlsx").Close SaveChanges:=False
Else
End If
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function

Using string as Named Table for Range Object

I have a list of text values each of which is the name of a Named Table on a different Worksheet of my Workbook.
Colum1 Value
Table1 True
Table2 False
Table3 False
Table4 True
Table5 True
My VBA code is going through the list like so:
For Each cell In MyRange
If cell.Offset(0, 1).Value = "True" Then
Call WriteTXTFile(cell.Value)
End If
Next cell
The WriteTXTFile subroutine needs to take the Table name and use it as a range to get all the data from the table and export it as a pipe-delimited TXT file like so:
Private Sub WriteTXTFile(TableName As String)
Dim TableRange As Range
Set TableRange = Range(TableName & "[#All]")
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim filesys, filenm, txtstrm
Dim CurrentCell As String
Set filesys = CreateObject("Scripting.FileSystemObject")
filesys.CreateTextFile ThisWorkbook.Path & "\" & TableName & ".txt"
Set filenm = filesys.GetFile(ThisWorkbook.Path & "\" & TableName & ".txt")
Set txtstrm = filenm.OpenAsTextStream(ForWriting, TristateFalse)
For Each cell In TableRange
CurrentCell = cell.Value
txtstrm.Write (Chr(124) & CurrentCell)
Next cell
txtstrm.Close
However, I keep getting an error:
"Method Range of object _Global failed."
I'm sure there's something wrong with the way the subroutine sets the TableRange, but I can't find any information on how to pass a Named Table name as a string to a subroutine and use it in a range.

Populate word from excel template each row=one document through bookmarks

I'm getting the error
"error 424" - object required
on the marked line:
Sub CreateWordDocuments1()
Const FilePath As String = "D:\"
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("word.application")
wApp.Visible = True
Dim PersonCell As Range
'create copy of Word in memory
Dim PersonRange As Range
'create a reference to all the people
Range("A1").Select
Set PersonRange = Range( ActiveCell, ActiveCell.End(xlDown))
'for each person in list �
For Each PersonCell In PersonRange
'open a document in Word
Set wDoc = wApp.Documents.Open("D:\template.doc")
'go to each bookmark and type in details
CopyCell "FirstName", 1
'save and close this document
wDoc.SaveAs2 FilePath & "person " & PersonCell.Value & ".doc"
wDoc.Close
Next PersonCell
wApp.Quit
MsgBox "Created files in " & FilePath & "!"
End Sub
Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark
wApp.Selection.GoTo What:=-1, Name:="FirstName" ''' Error on this line
wApp.Selection.TypeText PersonCell.Offset(0, ColumnOffset).Value
End Sub
Also, I am trying for whole day to skip this error but I can't. I search for some alternatives such as XML maybe?
The issues with your initial code:
Main error: variable wApp exists in CreateWordDocuments1, but
not in CopyCell
Variable PersonCell exists in CreateWordDocuments1, but not in CopyCell (same as 1st)
CopyCell doesn't use parameter BookMarkName (not critical but made it redundant)
.
Edited code to accommodate multiple Word bookmarks in synch with Excel columns
Here is how all files are setup - column names in Excel represent Bookmark names in Word:
.
Option Explicit
Public Sub CreateWordDocuments()
Const FILE_PATH As String = "C:\Tmp\"
Const FILE_NAME As String = "Template"
Const FILE_EXT As String = ".doc"
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim totalRows As Long 'assumes all columns are the same size
Dim totalCols As Long 'assumes all rows are the same size
Dim person As Long 'Outer loop counter (all rows)
Dim personList As Variant 'All data: rows and columns, without header row
Dim bookmark As Long 'Inner loop counter (all columns)
Dim bookmarks As Variant 'All bookmarks, from the header row
Set wApp = CreateObject("Word.Application")
wApp.Visible = False
'We're working in Sheet1, and data starts in its first cell (A1)
With ThisWorkbook.Worksheets(1)
With .UsedRange
bookmarks = .Rows(1).Value2 'get all column headers
totalRows = .Rows.Count
totalCols = .Columns.Count
End With
'all data without the header row -------------------------------------
personList = .Range(.Cells(2, 1), .Cells(totalRows, totalCols)).Value2
End With
For person = 1 To totalRows - 1 'each row (after header)
'Open Word Template file
Set wDoc = wApp.Documents.Open(FILE_PATH & FILE_NAME & FILE_EXT)
For bookmark = 1 To totalCols 'each column
With wApp.Selection
'bookmark name from header row
.GoTo What:=wdGoToBookmark, Name:=bookmarks(1, bookmark)
'enter data for each bookmark
.TypeText personList(person, bookmark)
End With
Next 'next column \ bookmark
With wDoc 'sava and close the new Word file (person name in column 1)
.SaveAs FILE_PATH & "Person " & personList(person, 1) & " " & personList(person, 2) & FILE_EXT
.Close
End With
Next 'next row
wApp.Quit
Set wDoc = Nothing
Set wApp = Nothing
MsgBox "Created " & totalRows - 1 & " files in " & FILE_PATH
End Sub