I have so far been able to activate a Word document embedded in Excel, but I'm not able to modify the table's preferredwidth. How can I access this property through Excel VBA?
Here's what i have so far
Sub ok()
Set WDObj = Sheets("Sheet1").OLEObjects("Object 4")
WDObj.Activate
WDObj.ActiveDocument.Tables(1).PreferredWidthType = wdPreferredWidthPercent
WDObj.ActiveDocument.Tables(1).PreferredWidth = 95
End Sub
In order to modify the content of an embedded Word document it's first necessary to access the embedded application, then the document itself. Once the code has accessed the OLEObject
it then needs the actual Object
, through which the application and the document can be addressed.
Note that it might be expedient to assign the OLE object a name, rather than relying on the one generated by Excel. Such names have a nasty tendency to change if additional objects are added or others deleted. Any name assigned explicitly will remain untouched. This needs to be run only one time on the worksheet (bases on the full sample code):
ws.OLEObjects("Object 4").Name = "WordDoc" 'for example, can be any string you prefer
Then, if you decide to do this, in the full code, it would be ws.OLEObjects("WordDoc")
At the end of the procedure the line ws.Cells(1, 1).Select
deactivates the embedded object by selecting a cell on the sheet. If you want to leave the Word document active for the user to work with, simply remove that line.
Sub ok()
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim doc As Object 'Word.Document
Dim wdObj As Object, wdTable As Object 'Word.Table
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
Set wdObj = ws.OLEObjects("Object 4")
wdObj.Activate
Set doc = wdObj.Object.Application.ActiveDocument
Set wdTable = doc.Tables(1)
wdTable.PreferredWidthType = 2 ' Word.WdPreferredWidthType.wdPreferredWidthPercent
wdTable.PreferredWidth = 95
ws.Cells(1, 1).Select
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.