我正在尝试创建一个excel函数,以将C4:K9单元格区域中包含的文本连接起来。
尽管下面的代码将文本合并在单元格范围内,但我未能在每行之间插入回车符(vbCrLF)。因此,当我在单元格中键入函数时,我希望看到输出值,我希望它成为C4:K4,回车符,C5:K5,回车符等内容,直到一个单元格中的C9:K9。
Function Join(rng As Range, delimiter As String) As String
Dim cell As Range, rowIndex As Long
For rowIndex = 1 To rng.Rows.Count
For Each cell in rng(cells(rowIndex,3), cells(rowIndex,11))
Join = Join & cell.Text & delimiter
Next cell
Join = Left(Join, Len(Join) - Len(delimiter)) & vbCrLF
Next rowIndex
End Function
有人对如何使此功能起作用有任何想法吗?
答案 0 :(得分:1)
要在一行中循环遍历每个单元格,可以执行以下操作:For Each cell In rng.Rows(rowIndex).Cells
。
要在一个单元格中显示多行,您需要vbLf
作为每行的最后一个字符(并以“自动换行”作为单元格格式)。
Function Join(rng As Range, delimiter As String) As String
Dim cell As Range, rowIndex As Long
For rowIndex = 1 To rng.Rows.Count
For Each cell In rng.Rows(rowIndex).Cells
Join = Join & cell.Text & delimiter
Next cell
Join = Left(Join, Len(Join) - Len(delimiter)) & vbLf
Next rowIndex
End Function
最后一个提示:请尽量避免使用内部VBA名称(Join,RowIndex)作为您自己的函数名称或变量。
答案 1 :(得分:0)
我已经更改了代码的For Each cell
行以使其起作用:
Function Join(rng As Range, delimiter As String) As String
Dim cell As Range, rowIndex As Long
For rowIndex = 1 To rng.Rows.Count
For Each cell In Range(rng(rowIndex, 1), rng(rowIndex, rng.Columns.Count))
Join = Join & cell.Text & delimiter
Next cell
Join = Left(Join, Len(Join) - Len(delimiter)) & vbCrLf
Next rowIndex
End Function
要了解它们之间的区别...我从您的台词开始:
For Each cell in rng(cells(rowIndex,3), cells(rowIndex,11))
-问题是我们使用的是新的Range
-它是rng
的子集,但它是新的,所以:
For Each cell In Range(rng(rowIndex, 1), rng(rowIndex, 9))
-很好,但是为了使它更具动态性,我将9换成了列数:
For Each cell In Range(rng(rowIndex, 1), rng(rowIndex, rng.Columns.Count))
答案 2 :(得分:0)
您用rowIndex = 1
给源单元寻址了错误。试试这个:
Function Join(rng As Range, delimiter As String) As String
Dim cell As Range, rowIndex As Long, colIndex As Long
For rowIndex = rng.Row To rng.Row + rng.Rows.Count - 1
For colIndex = rng.Column To rng.Column + rng.Columns.Count - 1
Join = Join & Cells(rowIndex, colIndex).Text & delimiter
Next
Join = Left(Join, Len(Join) - Len(delimiter)) & vbCrLf
Next rowIndex
Join = Left(Join, Len(Join) - 1) ' cut terminal crlf
End Function