How to write VBA to an XLSX file?
Posted: Fri Oct 11, 2019 10:21 am
Hi,
I'm having issues writing VBA to a new file , or read writing VBA in an existing file. I'm not sure if I'm doing something wrong or some sequence issue regarding settings.
Here is a sample application with 3 methods:
TestReadVBA - works fine
TestReadWriteVBA - fails
TestWriteVBA - fails
I'm having issues writing VBA to a new file , or read writing VBA in an existing file. I'm not sure if I'm doing something wrong or some sequence issue regarding settings.
Here is a sample application with 3 methods:
TestReadVBA - works fine
TestReadWriteVBA - fails
TestWriteVBA - fails
Code: Select all
program sample;
{$APPTYPE CONSOLE}
{$R *.res}
uses
XLSReadWriteII5,
BIFF_VBA5,
System.SysUtils;
procedure TestReadVBA(const Filename: string);
var
XLS: TXLSReadWriteII5;
ICount, IMacroLines: Integer;
begin
XLS := TXLSReadWriteII5.Create(nil);
try
Xls.ReadVBA := True;
XLS.LoadFromFile(Filename);
for ICount := 0 to (XLS.VBA.Count - 1) do
begin
Writeln('module: ' + XLS.VBA.Modules[ICount].Name);
for IMacroLines := 0 to (XLS.VBA.Modules[ICount].Source.Count - 1) do
begin
Writeln(XLS.VBA.Modules[ICount].Source.Strings[IMacroLines]);
end;
end;
finally
Xls.Free;
end;
end;
procedure TestReadWriteVBA(const Filename: string; const Newfilename: string);
var
XLS, XLS2: TXLSReadWriteII5;
begin
XLS := TXLSReadWriteII5.Create(nil);
try
XLS.ReadVBA := True;
XLS.LoadFromFile(Filename);
Xls.VBA.EditVBA := True;
with Xls.VBA.AddModule('mymodule2', VmtDocument).Source do
begin
Add('Public Function add(a As Integer, b As Integer) As Integer');
Add('add = a + b');
Add('End Function');
end;
Xls.SaveToFile(Newfilename);
finally
Xls.Free;
end;
end;
procedure TestWriteVBA(const Filename: string);
var
XLS: TXLSReadWriteII5;
begin
XLS := TXLSReadWriteII5.Create(nil);
try
Xls.VBA.EditVBA := True; // blows up because XlS.VBA is not initialised
with Xls.VBA.AddModule('mymodule2', VmtDocument).Source do
begin
Add('Public Function add(a As Integer, b As Integer) As Integer');
Add('add = a + b');
Add('End Function');
end;
XLS.SaveToFile(filename);
finally
Xls.Free;
end;
end;
begin
try
// works fine
TestReadVBA('sample.xls');
// problem appending
TestReadWriteVBA('sample.xls', 'sample_with_update.xls');
// problem appending vba to a new file
TestWriteVBA('new_sample.xls');
except
on E: Exception do
Writeln(E.Message);
end;
end.