Search code examples
matlabvbaactivexoffice-interop

Translate VBA syntax to Matlab for Activex control of Word document


I am a newbie to using activex controls in matlab. Am trying to control a word document. I need help translating between VBA syntax and Matlab, I think. How would one code the following in matlab?

Sub macro()
With CaptionLabels("Table")
        .NumberStyle = wdCaptionNumberStyleArabic
        .IncludeChapterNumber = True
        .ChapterStyleLevel = 1
        .Separator = wdSeparatorHyphen
End With

Selection.InsertCaption Label:="Table", TitleAutoText:="", Title:="", _
        Position:=wdCaptionPositionAbove, ExcludeLabel:=0
End Sub

Thanks, I looked at the help and the source but I am still feeling dense. I want to be able to control caption numbering and caption text in an automated report. Am using Tables and figures. I just can't quite get my head around how to code the addition of the captions.

The following code gets me part way there. But I don't have control over numbering style, etc,. I have tried to figure out the activex structure but I can't make sense of it. In particular, In particular the first bit the VB subroutine above.

% Start an ActiveX session with Word
hdlActiveX = actxserver('Word.Application');
hdlActiveX.Visible = true;
hdlWordDoc = invoke(hdlActiveX.Documents, 'Add');
hdlActiveX.Selection.InsertCaption('Table',captiontext);

Solution

  • After some fiddling, I think I got it to work:

    %# open Word
    Word = actxserver('Word.Application');
    Word.Visible = true;
    
    %# create new document
    doc = Word.Documents.Add;
    
    %# set caption style for tables
    t = Word.CaptionLabels.Item(2); %# 1:Figure, 2:Table, 3:Equation
    t.NumberStyle = 0;              %# wdCaptionNumberStyleArabic
    t.IncludeChapterNumber = false;
    t.ChapterStyleLevel = 1;
    t.Separator = 0;                %# wdSeparatorHyphen
    
    %# insert table caption for current selection
    Word.Selection.InsertCaption('Table', '', '', 0, false) %# wdCaptionPositionAbove
    
    %# save document, then close
    doc.SaveAs2( fullfile(pwd,'file.docx') )
    doc.Close(false)
    
    %# quit and cleanup
    Word.Quit
    Word.delete
    

    Refer to the MSDN documentation to learn how to use this API. For example, the order of arguments of the InsertCaption function used above.

    Note that I had to set IncludeChapterNumber to false, otherwise Word was printing "Error! No text of specified style in document" inside the caption text...

    Finally, to find out the integer values of the wd* enums, I am using the ILDASM tool to disassemble the Office Interop assemblies (as this solution suggested). Simply dump the whole thing to text file, and search for the strings you are looking for.

    ildasm