定义大型vba字符串的最佳方法 - 即heredoc等价物?

Oes*_*sor 15 vba

我应该如何在VBA中定义大字符串?有没有比编码下面更好的方法?

Dim largeString as String
largeString = "This is a long block of text that I want to fill " & _
              "into a form field. I need to make sure I pay attention " & _
              "to spacing and carriage return issues while doing so. " & _
              "I also have to use quotes liberally, the concatenation " & _
              "operator, and the continuance underscore to make sure " & _
              "VBA can parse my code." & vbCr & vbCr & _
              "It's kind of a pain in the ass and I wish I could use " & _
              "a heredoc instead, letting me copy and paste the block" & _
              "of text I need from another source and shove it into " & _
              "a string."
Run Code Online (Sandbox Code Playgroud)

编辑:呃,还有25行延续限制吗?非常好的缩进和80个字符的宽度,这只给了我足够的空间,几个体面的段落.

Dir*_*mar 12

不,这很好.

对于非常长的字符串,可以选择将字符串保存在单独的文件中,或使用某些应用程序功能.例如,在Word中,您可能希望将字符串存储在文档变量中,作为隐藏文本或自动图文集.在Excel中,您可能会考虑使用隐藏工作表来存储长字符串常量.


小智 11

我更喜欢这样做:

Dim lStr As String
lStr = ""

lStr = lStr & "This is a long block of text that I want to fill "
lStr = lStr & "into a form field. I need to make sure I pay attention "
lStr = lStr & "to spacing and carriage return issues while doing so. "
lStr = lStr & "I also have to use quotes liberally, the concatenation "
lStr = lStr & "operator, and the continuance underscore to make sure "
lStr = lStr & "VBA can parse my code." & vbCr & vbCr
lStr = lStr & "It's kind of a pain in the ass and I wish I could use "
lStr = lStr & "a heredoc instead, letting me copy and paste the block"
lStr = lStr & "of text I need from another source and shove it into "
lStr = lStr & "a string."
Run Code Online (Sandbox Code Playgroud)

我认为这种方法比行继续方法更容易使用,并且没有行号限制以这种方式进入.您可以注释掉各行,这对调试SQL字符串很有用.

处理长字符串时,我发现使用短变量名更容易,因为VBA没有等效的+=运算符. largeString = largeString & ""占用太多空间并且重复,因此缩短字符串名称使格式有点可忍受.

对于非常大的文本块,将其写入文本编辑器,然后将其复制并粘贴到您的过程中.然后复制

lStr = lStr & "
Run Code Online (Sandbox Code Playgroud)

并将其粘贴在每行的开头.VBA编辑器将自动在行尾添加引号,使流程变得简单.

  • 我喜欢这种用于行连续的语法,但是我问“为什么”,为什么有人需要一个无法放在其他地方的大字符串?而且,这让我想起了所有认为编程的高度是串联的VBA强盗。 (2认同)