Excel VBA中的字符串连接失败,出现运行时错误

时间:2018-04-17 09:48:36

标签: excel vba string-concatenation

为什么:

sDesktopPath = Environ("USERPROFILE") & "\Desktop\"
sTimeStamp = Format(Now(), "yyyymmdd-hh:nn")
sSuffix = "_1Sheet_" & sDateTimeNow

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    sDesktopPath & ActiveSheet.Range("E3").Value & "_1Sheet_" & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=True

没有问题的工作,但是:

sDesktopPath = Environ("USERPROFILE") & "\Desktop\"
sTimeStamp = Format(Now(), "yyyymmdd-hh:nn")
sSuffix = "_1Sheet_" & sDateTimeNow

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    sDesktopPath & ActiveSheet.Range("E3").Value & "_1Sheet_" & sTimeStamp & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=True

因运行时错误而失败?

enter image description here

如果我使用sSuffix代替"_1sheet_" & TimeStamp,我会遇到同样的问题。

VBA编辑器将错误显示为Export...语句的最后一行,但该行中没有任何更改,我看不到任何在它之前发生的更改会破坏语法。< / p>

enter image description here

1 个答案:

答案 0 :(得分:0)

每当发生类似这样的事情时,请尝试调试整个字符串。因此:

Debug.Print sDesktopPath & ActiveSheet.Range("E3").Value & "_1Sheet_" & sTimeStamp & ".pdf" 

您会看到sTimeStamp是“非法的”,包含:。因此,请更改时间戳:

sTimeStamp = Format(Now(), "yyyymmdd-hh:nn")

要:

sTimeStamp = Format(Now(), "yyyymmdd-hhnn")