我正在努力解决一个涉及明显 Excel 255 个字符限制的常见问题。尝试将变体数组从函数返回到工作表上的选定范围时遇到错误。当函数返回数组中的每个单元格都小于 255 个字符时,它们会按应有的方式发布到工作表:一个元素出现在所选范围内的每个单元格中。但是,如果我返回的变量数组中的任何元素长于 255 个字符,我会得到一个值!错误。这些错误很糟糕,因为我需要我的长元素并希望将数据保持在一起!
这个问题的版本在许多论坛中一遍又一遍地出现,但是当数组单元格超过 255 个字符时,我能够找到一个清晰简单、通用的解决方案,用于将变体数组返回到所选范围(不一定包含公式)。我最大的元素大约是 1000 个,但如果解决方案可以容纳最多 2000 个字符的元素会更好。
最好,我希望用一个函数或可以添加到我的函数(不是子例程)的附加代码行来实现它。我想要避免子例程的原因:我不想对任何范围进行硬编码。我希望这是灵活的,并且输出位置可以根据我当前的选择动态地进行。
拜托,如果您能帮助找到一种方法来生成一个函数,该函数将变量数组作为输入,并保持所需的数组:单元格 1:1 关系,我将不胜感激。
所以这个带有短单元的功能有效:
Function WriteUnder255Cells()
Dim myArray(3) As Variant 'this the variant array I will attempt to write
' Here I fill each element with less than 255 characters
' it should output them if you call the function properly.
myArray(0) = "dog"
myArray(1) = "cat"
myArray(2) = "bird"
myArray(3) = "fly"
WriteUnder255Cells = Application.Transpose(myArray())
End Function
但是这个函数,超过 255 的单元格将不会输出。
Function WriteOver255Cells()
Dim myArray(3) As Variant 'this the variant array I will attempt to write
' Here I fill each element with more than 255 characters
' exceeding the 255-character limit causes the VALUE! errors when you output them
myArray(0) = "ThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelaxydog"
myArray(1) = "ThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydog"
myArray(2) = "ThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydog"
myArray(3) = "ThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydogThequickbrownfoxjumpedoverthelazydog"
WriteOver255Cells = Application.Transpose(myArray())
End Function
这是生成输出和结果的方式:
首先,您需要创建两个模块(要将一个函数插入每个模块,将代码从一个模块粘贴到相应的模块中)。要运行“WriteUnder255Cells()”,请在工作表上选择一个 4 行 x 1 列的区域(返回模块的位置),然后在公式栏中输入“=WriteUnder255Cells()”(不要输入引号)。请注意,这些被称为数组公式,因此您需要点击 (control + shift + enter)而不是点击 (enter) 来创建输出。对 WriteOver255Cells() 重复相同的过程以产生错误。
以下是一些解决该问题的文档/论坛讨论。这些解决方案似乎过于具体或笨拙,因为它们会引发子例程(我想避免):
https://support.microsoft.com/en-us/kb/213841
http://dailydoseofexcel.com/archives/2005/01/10/entering-long-array-formulas-in-vba/
https://forums.techguy.org/threads/solved-vba-access-to-excel-255-char-limit-issue.996495/