Excel VBA遍历列到AA列时代码停止运行问题咨询
报错原因
Chr()函数仅能转换ASCII码65-90对应的单字母列名A-Z,当遍历到Z列之后的AA列时,对应的ASCII码超过90,Chr()返回的是[、\等非字母符号,构造的Range地址非法导致代码中断。
修正后代码
Sub Resultas_ELEC() Dim colNum As Integer ' 遍历范围为G列(列号7)到AD列(列号30),共24列,和原逻辑遍历范围完全一致 For colNum = 7 To 30 Cells(77, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=S") Cells(78, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=E") Cells(79, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=E-S") Cells(80, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=E-E") Cells(81, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=E-A") Cells(82, colNum) = Application.WorksheetFunction.CountIf(Range(Cells(7, colNum), Cells(73, colNum)), "=A") Next colNum End Sub
修改说明
- 放弃通过ASCII转换列名字符串的方案,直接使用Excel原生列号索引定位列,支持所有合法列范围,无需处理多字母列名转换逻辑
- 删除了冗余的重复变量声明,仅保留
colNum控制遍历逻辑 - 完全保留原代码的统计规则、写入位置、遍历范围,和原有业务需求完全匹配
- 代码执行效率更高,无非法地址构造风险
内容的提问来源于stack exchange,提问作者user9626650
相关产品推荐
相关产品推荐

