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

时间:2010-09-08 19:40:29

标签: 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."

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

4 个答案:

答案 0 :(得分:12)

不,这很好。

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

答案 1 :(得分: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编辑器将自动在行尾添加引号,使流程变得简单。

答案 2 :(得分: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

答案 3 :(得分:0)

在 Excel 中,这里有一个比其他答案更简单的方法。让 Excel 为您完成繁重的工作。这种方法不需要将字符串分成更小的块——它一次最多可以处理 32,767 个字符。

将字符串放入一个单元格中。命名单元格,例如MyLongString。现在您可以将 VBA 中的名称称为 [MyLongString]。例如:

MsgBox [MyLongString]