Excel VBA函数sGetPreTag_Simple()返回TRUE/FALSE而非输入值的问题求助
Excel VBA函数sGetPreTag_Simple()返回TRUE/FALSE而非输入值的问题求助
嗨,我一眼就揪出问题所在了——这是新手很容易踩的语法小坑,咱们分分钟搞定它!
你的核心问题出在sGetPreTag_Simple函数的赋值语句里:
sGetPreTag_Simple = Str(Date) + " (" + Environ("UserName") + ") " = ":" + vbLf + sNewValue + vbLf + "------------" + vbLf
这里的=是比较运算符,不是用来拼接内容的!VBA会把整个式子当成「左边的字符串是否等于右边的字符串」来做判断,结果自然是布尔值TRUE或FALSE,而不是你想要的拼接好的备注文本。
修正后的函数代码
把中间的=换成字符串连接符&(更推荐用&而非+,因为+在混合字符串和数值时容易出问题,&是专门的字符串连接符),同时调整标点位置让格式更合理:
Private Function sGetPreTag_Simple() As String Dim sNewValue As String sNewValue = InputBox("Enter new note", "PreTag Simple", "") If sNewValue <> "" Then ' 替换错误的=为&,同时调整冒号位置让格式更规范 sGetPreTag_Simple = Str(Date) & " (" & Environ("UserName") & "):" & vbLf & sNewValue & vbLf & "------------" & vbLf Else sGetPreTag_Simple = "" End If End Function
额外小优化(可选)
你的PreTag_Simple子过程里,判断单元格值的部分可以简化:
Sub PreTag_Simple() Dim rngSelection As Range Dim sValue As String Dim sNewValue As String Set rngSelection = Selection With ActiveSheet.Cells(rngSelection.Row, rngSelection.Column) ' 用CStr直接转换,不用分情况判断日期/数值 sValue = CStr(.Value) sNewValue = sGetPreTag_Simple() If sNewValue <> "" Then .Value = sNewValue & sValue End If End With End Sub
这样修改后,再运行快捷键,输入的备注就会正确拼接日期、用户名和原有单元格内容,再也不会返回奇怪的布尔值啦!
备注:内容来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

