D
D
docbrain2016-10-09 18:29:34
Delphi
docbrain, 2016-10-09 18:29:34

The code that writes a macro to a Word document crashes with an incomprehensible error. Why?

Good time of the day. I have a Delphi code that needs to write a macro to Word documents:

const

  vbext_ct_StdModule = 1;

  wdFormatXMLDocumentMacroEnabled = 13;
var
  wdApp, wdDoc, wdVbProj, wdVbModule, wdVbCode : OleVariant;
  FName : String;
  I : Integer;
  begin
  try
    wdApp := CreateOleObject('Word.Application');
    finally
    end;
  wdApp.Visible := False;
  for I := 0 to ListBox1.Count -1 do
  begin
  wdDoc := wdApp.Documents.Open(ListBox1.Items[I]);
    wdVbProj := wdDoc.VBProject;
  wdVbModule := wdVbProj.VBComponents.Add(vbext_ct_StdModule);
  //wdVbModule.Name := 'VBModule1';
  wdVbCode := wdVbModule.CodeModule;
  wdApp.DisplayAlerts := False;
  try
    wdVbCode.DeleteLines(1, wdVbCode.CountOfLines);
    wdVbCode.AddFromString(Memo1.Text);
    finally
    wdApp.DisplayAlerts := True;
    end;
    FName := ListBox1.Items[I] ;
    FName := LeftStr(FName, Length(FName) - Length(ExtractFileExt(FName))) + '.docm';
    wdApp.DisplayAlerts := False;
      wdDoc.SaveAs(FileName:=FName, FileFormat:=wdFormatXMLDocumentMacroEnabled);
      wdApp.DisplayAlerts := True;
wdDoc.Close;
end;
  wdApp.Quit;
end;

however, when I run it for execution, for some reason it crashes with an error: "The file is corrupted", and it does not write which file. The Delphi debugger blames this line for everything:
wdDoc := wdApp.Documents.Open(ListBox1.Items[I]);
At the same time, when I try to access the file not through ListBox1.Items, but directly, everything works fine. What is the matter here and how to make the code work as it should?
PS Just in case, here's another code that writes data to the ListBox:
procedure TForm1.FindFilePattern(root, pattern: String);
var
SR:TSearchRec;
Ext : String;
begin
root:=IncludeTrailingPathDelimiter(root);
  if FindFirst(root+'*.*',faAnyFile,SR) = 0 then
  begin
      repeat
          Application.ProcessMessages;
          if ((SR.Attr and faDirectory) = SR.Attr ) and (pos('.',SR.Name)=0) then
             FindFilePattern(root+SR.Name,pattern)
          else
          begin
           Ext := AnsiUpperCase(ExtractFileExt(SR.Name));
         
           if (Ext = '.DOCX') then
           begin
          
           ListBox1.Items.Add(Root + SR.Name);
           end;
          end;
      until FindNext(SR)<>0;
  end;
end;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question