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

问题描述 投票:14回答:3

我应该如何在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."

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

vba
3个回答
12
投票

不,这很好。

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


10
投票

我更喜欢这样做:

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."

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

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

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

lStr = lStr & "

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


0
投票

另一种方法是将文本存储在注释中,然后在函数中解析它。无需外部文件,可读性好。

' TEXT to retrieve:
'   SELECT
'   field1, field2
'   FROM table1

Function SQL_in_comments()
    SQL_in_comments = Replace(Replace(Application.VBE.ActiveCodePane.CodeModule.Lines(2, 3), "'   ", ""), "'", "")
End Function
© www.soinside.com 2019 - 2024. All rights reserved.