首页 > 解决方案 > 用于连接的 Excel VBA 函数不返回有效的单元格结果(但 debug.print 显示正确的字符串)

问题描述

没有经验的 Stackoverflow 用户,如果需要,请随时将我指向其他论坛或子论坛。

我创建了以下 VBA(然后还在线查看了其他代码示例,它们似乎都遵循相同的逻辑)。我在调试窗口中测试并准确看到我期望的结果(多行字符串)。但是,当我在工作表单元格中键入公式时,我收到 #Value 错误。

任何想法为什么不使用公式填充回单元格?

Function ConcatCells()
    
    'just to be safe, clear the string
    ConcatCells = ""
    
    'Loop and add each cell text with a line break
    For Each cell In Selection
        ConcatCells = ConcatCells & Chr(13) & cell.Text
    Next
    
    'remove the leading line break
    ConcatCells = Right(ConcatCells, Len(ConcatCells) - 1)
    
    'is the string actually being created correctly? Yes
    Debug.Print ConcatCells
    
End Function

标签: excelvbastring-concatenation

解决方案


Selection As Range作为参数 添加到您的函数中:Function ConcatCells(Selection As Range)

在此之后,您的函数将返回如下值:OneTwoThreeFourFive

当您复制此单元格并粘贴为值时,

在点击F2and之后Enter,你会看到这样的视图:

在此处输入图像描述


推荐阅读