Delphi Tokyo - I am using Delphi to do some Excel spreadsheet pre-processing prior to a load operation. I am trying to read an Excel Range into a VarArray, loop through the array to do cleanup (in this case, it is a zip code column. If it is a 4 digit zipcode, prefix a '0'), and then write the VarArray back to the Excel range. Everything compiles, but I get an error message on the first access of the VarArray. The specific error is 'Variant or safe array index out of bounds'. My VarArray starts at row 2 of the excel range. Any idea why I am getting this error? I have tried to simplify the code as much as possible here....
function PROCESS_ZIP_CODE_5DIGIT_MIN(P1,P2 : String): integer;
var
MyColumnLetter : String;
thisSheet : _Worksheet;
i : Integer;
CellText : String;
arrData: Variant;
myRange : ExcelRange;
RangeStartAddr, RangeEndAddr : String;
begin
MyColumnLetter := 'H';
thisSheet := oExcel.ActiveSheet as _Worksheet;
{create variant array where we'll copy our data}
arrData := VarArrayCreate([2, 500 ], varVariant);
// Get the Range Address
RangeStartAddr := MyColumnLetter + '2';
RangeEndAddr := MyColumnLetter + IntToStr(500);
// Now read the data into the VarArray
myRange := thisSheet.range[RangeStartAddr, RangeEndAddr];
arrData := myRange.Value2;
// Now process the data itself
for i := 2 to 500 do
begin
CellText := arrData[i]; // ERROR ON THIS LINE
if Length(CellText) = 4 then
begin
CellText:= '0' + CellText;
arrData[i] := CellText;
end;
end;
// Now write the VarArray back to the spreadsheet
thisSheet.range[RangeStartAddr, RangeEndAddr].Value2 := myRange;
end;
arrData := VarArrayCreate([2, 500 ], varVariant);you assign a value to arrData witharrData := myRange.Value2;, that assignment is overwriting you var array. Does this return an array of var, too?VarArrayCreate. I think the call toVarArrayCreateis not necessary. And the new array could have different bounds. These must be checked before entering the loop.MyColumnLetter + '2'), while they use numbers:[wb.workSheets[1].Cells[1, 1], etc...]. Are you sure you receive anything? And you may need a two-dimensional array too, even if the second dimension is only 1 in size. Just try their exampe verbatim, and then modify it to your needs, constantly checking if it still works. If something goes wrong, you know what you did last and that must be the problem.