问题描述
您在Excel中知道列名称是字母。当到达Z时,它将继续使用AA-AB-AC。是否可以在Delphi XE7 + for循环中实现类似的功能?
我尝试过:
var
i:integer;
str:string;
begin
str:='a';
for i := 0 to 26-1 do
begin
inc (str,1);
memo1.Lines.Add(str);
end;
但它返回了:
[dcc32 Error] FBarkodsuzIndesignVerisiOlustur.pas(249): E2064 Left side cannot be assigned to
我认为那是因为str不是整数。
我可以使用此功能将数字转换为字母:
function numberToString(number: Integer): String;
begin
Result := '';
if (number < 1) or (number > 26) then
Exit;
Result := 'abcdefghijklmnopqrstuvwxyz'[number];
end;
但是我不知道当超过26时如何创建AA之类的字母。
同样采用以下方法,它会创建26个字母,但是当它超过26个时,它将开始使用方括号之类的字符:
for i := 0 to 27-1 do
begin
memo1.Lines.Add(Char(Ord('a') + i));
end;
输出:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
到达Z时,它将继续显示为“ AA”,“ BB”,“ CC”,依此类推,例如Excel会创建列名。
解决方法
这是我用于任务的功能。
function SpreadSheetColName(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c,Col);
Result := c;
end else begin
Result := SpreadSheetColName(Col div 26 - 1) + SpreadSheetColName(Col mod 26);
end;
end;
请注意,它使用从零开始的索引。我建议您在整个编程过程中也将基于零的索引用作一般规则。
如果您无法做到这一点,那么基于一个的版本将如下所示:
function SpreadSheetColName(const Col: Integer): string;
function SpreadSheetColNameZeroBased(const Col: Integer): string;
var
c: Char;
begin
Assert(Col >= 0);
if Col<26 then begin
c := 'A';
Inc(c,Col);
Result := c;
end else begin
Result := SpreadSheetColNameZeroBased(Col div 26 - 1) + SpreadSheetColNameZeroBased(Col mod 26);
end;
end;
begin
Result := SpreadSheetColNameZeroBased(Col - 1);
end;