我对 Excel 中的 VBA 不太熟悉。我需要返回 VBA 函数文本值,无论字符限制如何(如果需要限制,560 就足够了)。我读过很多关于 255 个字符限制和换行文本或使用不同字符串等的论坛帖子,但我不太明白如何将其实现到我下面使用的代码中。
情况: 我每天都有一堆文件(纸质副本),每个文件都有一个 7 位数的数字 ID。其长度始终为 7 位数字。我在单元格 B4 中键入不带空格或逗号的值,然后在单元格 B5 中通过 =InsertChar(B4) 调用该函数,该函数将用逗号分隔每个文档 ID(每 7 位)。我从网上复制的以下代码完美地完成了这项工作,每 7 位数字都会插入一个逗号,直到单元格 B5 超过 255 个字符,在这种情况下它将返回“#VALUE!”。 p>
我尝试格式化单元格并添加一些换行代码(确实对文本进行了换行),但一旦单元格 B5 超过 255 个字符,它仍然返回“#VALUE!”而不是数字和逗号作为文本。
如果有人能提供帮助,我将不胜感激。似乎是一个简单的修复,但我是 VBA 的新手,甚至不理解我使用过的一半代码。 :)
注意:Office Excel 2016 版和 365。
单元格 B4(手动输入的虚拟数据,不带逗号): ojit_代码
VBA 代码:
Option Explicit
Function InsertChar(STR As String, Optional sInsertCharacter As String = ",", Optional lSpacing As Long = 7) As String
Dim sCharString As String
Dim sFormatString As String
Dim sTemp As String
Dim I As Long
For I = 1 To lSpacing
sCharString = sCharString & "&"
Next I
sCharString = sCharString & sInsertCharacter
For I = 0 To Len(STR) \ lSpacing
sFormatString = sFormatString & sCharString
Next I
sFormatString = "!" & Left(sFormatString, Len(sFormatString) - 1)
sTemp = Format(STR, sFormatString)
If Right(sTemp, 1) = "," Then sTemp = Left(sTemp, Len(sTemp) - 1)
InsertChar = sTemp
End Function
单元格 B5(当少于 255 个字符时,VBA 函数的正确结果): ojit_代码
单元格 B5(当超过 255 个字符时,VBA 函数的结果不正确): ojit_代码
最佳答案
看起来错误是因为 Format
函数可以处理的字符限制。
您需要考虑另一种不使用Format
的方法。例如,
Function InsertChar(STR As String, Optional sInsertCharacter As String = ",", Optional lSpacing As Long = 7) As String
Dim RestChars As String
RestChars = STR
Do While RestChars <> ""
InsertChar = InsertChar & Left$(RestChars, lSpacing) & sInsertCharacter
If Len(RestChars) > lSpacing Then
RestChars = Right$(RestChars, Len(RestChars) - lSpacing)
Else
RestChars = ""
End If
Loop
InsertChar = Left$(InsertChar, Len(InsertChar) - 1)
End Function
关于Excel VBA (UDF) 返回#VALUE!由于 255 个字符的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098840/