Excel VBA Centering contents in a Word Document table - excel

I am creating a macro in Excel that inserts a table in Word at a specific bookmark. The table insertion process and the process that updates the table is working like I expect it to.
Now, I'm trying to align the data in the table. I'm using the following code to align the data in the table cells:
objTbl.Cell(i, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
objTbl.Cell(i, 1).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
This works great and is exactly how I want the data to appear.
The only issue I'm having is the data appears at the top of each cell and I would like it in the middle of each cell. Is this possible? I tried to adjust the row height with the following code:
WrdApp.ActiveDocument.Tables(1).Rows.Height = 15
I've tried both 15 and 20 and it didn't make a difference.
My VBA experience has been overwhelmingly within Excel. So this is a bit of a learning curve to program Word from Excel. Any suggestions would be appreciated. Thanks in advance for your help.......

Perhaps you should spend part of your 60 minutes of research in recording a macro. Whilst you wouldn't want to use the recorded code it will point you to the objects and properties you need to use. Of course you do need to know how to use the UI to achieve what you want first.
Sub CellAlignment()
'
' CellAligment Macro
'
'
Selection.SelectCell
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.Cells.VerticalAlignment = wdCellAlignVerticalCenter
End Sub
Having recorded the code you can then use the online help or the object explorer to get a pointer to more usable code, e.g.
ActiveDocument.Tables(1).Range.Cells.VerticalAlignment = wdCellAlignVerticalCenter

Related

Excel VBA How to search through a table and display results on listbox

I've been wanting to show a filtered data on a listbox from the word that I search for from a table. Currently I have the following code:
'First, setting a as the word I want to search through the first column of the table'
Set a = Sheets("Main").Range("P14")
'setting Enertec Fee'
If a = "ENERTEC" Then
frmFeee.lstAHK.RowSource = "AHK_Fee!A6:D9"
frmFeee.lstMD.RowSource = "AHK_MD!A6:D9"
End If
This works but I realised that if I want to add new data on the table, it'll not be updated on the listbox unless I change the code everytime. Is there a better way of going about this?
Any help would be greatly appreciated !
I've attached some pictures to help.
listbox displaying results
Thank you.

How to position a chart copied from excel into powerpoint using CommandBars?

I am trying to copy some charts (embedded) in different worksheets of an excel workbook using vbscript into different slides of a powerpoint. I would like to keep the link between the excel sheet and the powerpoint while doing so and therefore I used the below piece of code that allows me to keep formatting and link (instead of a simple paste or PasteSpeical. Is there any other way?) :
For i = 1 to TotalNumWorkSheets 'I iterated with indices.
Set pptSlide = pptPres.Slides.Add(i, 11) 'There is one opening slide before this.
set ws = wb.Worksheets(i)
ws.ChartObjects(1).Chart.ChartArea.Copy
pptApp.CommandBars.ExecuteMso("PasteExcelChartSourceFormatting")
pptApp.CommandBars.ReleaseFocus
With pptSlide
.Shapes.Title.TextFrame.TextRange.Text = objCurSheet.Name
'Adding some more textboxes here. Working fine. Position checks out in PPT.
.Shapes(.Shapes.Count).Left = 20 'Doesn't work for all slides.
End With
Next
The code works and copies all the charts, creates titles, adds new text as expected, but I am not able to position the charts on individual slides because after the ExecuteMso command, I don't know how to access the reference to the chart. I read in one of the SO posts that pasting using this method looses the chart selection but you can access the last .Shapes object since pasting always adds the object to the end of the list. Is that always the case? I tried accessing and positioning my chart by accessing the last object but it only works for the first slide of the loop (i.e. the first chart pasted is shifted to Left=20). The rest all charts in other slides are centered. Can someone explain where and how to add the formatting chart options? I ran into an even weirder problem. If I increase the number of worksheets, even the first plot looses it's Left formatting. The above code is the only place where I add formatting so I don't know what is happening. I am sure I am not formatting it correctly.
Many thanks for your suggestions.
Edit: One additional thing which I tested. I am using
WScript.Sleep 500
code before the For loop ends since it gives enough time for earlier operations to finish (at least that's what I understood from many other google searches).
So after some more searching and testing, I found a solution (for my case at least).
Moved the WScript.Sleep 1000 (500 didn't work for me) statement just below CommandBars.ReleaseFocus.
It makes some sense now since it is the Chart copying, pasting and linking from excel that needs time. Especially with source formatting. After that there is only text generation which I believe is not so heavy.
Cleared all the set Object variables when not used. Especially the ones associated with the "With" keyword.
set obj = CreateObject()
With obj
'Do something here.
End With
set obj = Nothing
Not clearing them, apparently, can also prevent you from closing the applications even after you use the .Close and .Quit method. At least that's what I observed. I found PowerPoint.exe running in the task manager when nothing was opened.
After doing the above, I am able to copy with format the charts and also able to set the position of the charts. The weird problem of larger number of worksheets also disappeared. Hopefully, it might help others. If someone thinks the observations are incorrect or troublesome, please correct.

Embed excel into word using vba does not always display the top of the embedded sheet

I have a Word document with VBA code to embed multiple excel sheets using the following process i.e. addOLEObject
Set IllSheet = _
ActiveDocument.Bookmarks("example1").Range.InlineShapes.AddOLEObject(ClassType:="Excel.Sheet.12", filename:=filename1, LinkToFile:=False)
however on occasion the embedded spreadsheet does not display at the top of the sheet but seemingly randomly scrolled part way down the sheet. I have checked and the excel sheet is saved with it scrolled to the top.
How can I ensure the sheet embedded is always scrolled to the top?
I can access the embedded sheet and input values as per below but can not seem to find a suitable line of code to ensure that the sheet displays at the top of active sheet.
Set objOLE = ActiveDocument.InlineShapes(3).OLEFormat
objOLE.Activate
objOLE.Object.ActiveSheet.Cells(1, 3).Value = Format(Funds, "#,###0")
Selection.MoveRight
objOLE.Object.Application.Quit
DoEvents
I have tried scroll functions etc and also want to avoid using SendKeys because it is so unreliable.
Any help greatly appreciated.
M

Deleting watermark in Word from Excel VBA (redux) Difference between Word & Excel VBA

[There is another recent question with a similar title that has not yet been answered satisfactorily, and gave me no insight :-( ]
This is my first attempt to integrate a little Word automation with Excel VBA, so I started with a macro recording in Word VBA to have a clue. Unfortunately, when I try to translate this into Excel, even making allowances for having to use the Excel local wrdDoc to qualify references, the code that works in Word VBA does not work from Excel VBA. Deeply frustrating.
Here is the recorded code snippet from Word that I started with:
[Shape name manually edited after recording to match assigned name for the Watermark image]
ActiveDocument.Sections(1).Range.Select
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.HeaderFooter.Shapes("US-CA watermark").Select
Selection.Delete
Here is the code snippet from Excel I derived from that:
[sWatermark string predefined to match the picture name]
With wrdDoc
.Sections(1).Range.Select
.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
.Selection.HeaderFooter.Shapes(sWatermark).Select
.Selection.Delete
End With
Result: VBA chokes every time when I try to select the watermark (line 3 within the With block).
I have tried the problem line with and without the . prefix [i.e. as wrdDoc.Selection and just Selection (as in the original Word macro) ].
I have tried accessing the watermark as .HeaderFooter.shapes(1) after verifying that there is only 1 item in the range. Again, this seems to work quite satisfactorily in Word VBA, but never in Excel VBA.
WHY?!?!?!
Avoid using the Selection when possible, as it can be changed during macro execution. For example:
wrdDoc.StoryRanges(wdPrimaryHeaderStory).ShapeRange(1).Delete

Excel 2007 Display image from image path?

I would like to insert an image into a cell.
The code below inserts it into a sheet:
With wb.Sheets(1).Pictures.Insert("\\bk01fil0001\salesdb$\ImageUpload\NoImage.gif")
.Left = wb.Sheets(1).Range("B2").Left
.Top = wb.Sheets(1).Range("B2").Top
.Width = wb.Sheets(1).Range("B2").Width
End With
You can't insert a picture inside a cell: they always sit "on top" of the worksheet. Best you can do is position it over the required cell/range as you are already doing.
You can make things a little simpler by selecting a cell then inserting the picture...
Sheets(1).Select
Range("B2").Select
ActiveSheet.Pictures.Insert("\\bk01fil0001\salesdb$\ImageUpload\NoImage.gif")
I don't think this would ever be a less efficient method as you would only ever wish to insert a picture on a visible sheet. I do not see you would need to select the sheet more than once, if at all
(As an aside, it sounds as though you are trying to auto-insert images in one column of a table in which case I would strongly recommend using Cells notation as described in the text accompanying this Excel Visual Basic video)

Resources