DIM p_str,p_num
p_str = ""
p_num = 0 '定义变量,标记中文为2字节时的实际字符数
IF TRIM(str)<>"" THEN
FOR i = 1 TO num
IF asc(mid(str,i,1))>255 OR ASC(mid(str,i,1))<0 THEN '判断下一个欲取的字符所占字节数
p_num = p_num + 2
Else
p_num = p_num + 1
End IF
IF p_num > num THEN EXIT FOR
NEXT
p_str = Left(str,i-1) '把i-1替换为i,则产生与“说明”中相反的情况。
END IF
strLeft=p_str
END FUNCTION
'--------------------******END******--------------------
可是在实际使用中发现cheery_ke兄提供的程序有些问题:如果提交的字符串字数少于所允许的最大字数则程序汇报错,原因是 FOR 循环处的循环次数大于字符串的实际长度,导致下一句中mid函数的参数 i 大于字符串的长度,出现错误。
我针对这个程序作了如下改进:
function strLeft(str,num)
dim p_str,p_num
p_str = ""
p_num = 0
if trim(str) <> "" then
p_len = len(str)
for i = 1 to p_len
if asc(mid(str,i,1)) > 255 or asc(mid(str,i,1)) < 0 then
p_num = p_num + 2
else
p_num = p_num + 1
end if
if p_num > num then
p_str = Left(str,i-1)
exit for
else
p_str = str
end if
next
end if