VBA中导入字符串到公式返回FALSE问题排查
问题分析与解决
核心错误出在公式赋值的语句上,你在给.Formula赋值时,错误地在末尾加了= "",这会让VBA把整个表达式当成比较运算:把"=Sum(" & strGreen & ")"和空字符串对比,结果是布尔值FALSE,所以单元格最终显示FALSE而非公式。
修正后的关键代码
把这三行错误的赋值语句:
.Cells(d, LastColumn + 3).Formula = "=Sum(" & strGreen & ")" = "" .Cells(d, LastColumn + 4).Formula = "=Sum(" & strOrange & ")" = "" .Cells(d, LastColumn + 5).Formula = "=Sum(" & strBlue & ")" = ""
替换为:
'Green If strGreen <> "" Then .Cells(d, LastColumn + 3).Formula = "=Sum(" & strGreen & ")" Else .Cells(d, LastColumn + 3).Value = "" ' 也可根据需求设为0 End If 'Orange If strOrange <> "" Then .Cells(d, LastColumn + 4).Formula = "=Sum(" & strOrange & ")" Else .Cells(d, LastColumn + 4).Value = "" End If 'Blue If strBlue <> "" Then .Cells(d, LastColumn + 5).Formula = "=Sum(" & strBlue & ")" Else .Cells(d, LastColumn + 5).Value = "" End If
额外优化说明
- 增加空字符串判断:如果某颜色没有匹配的单元格,对应的字符串变量会是空值,直接赋值
=Sum()会触发Excel公式错误,加判断可以避免这种情况。 - 你原本的单元格地址拼接逻辑是正确的,无需改动,只需修正赋值语句的语法错误即可。
内容的提问来源于stack exchange,提问作者Error 1004
相关产品推荐
相关产品推荐

