Excel 连接选定的行并输出到新列
问题描述
我正在尝试创建一个宏,它将连接我选择的行中的值(可以是2行到5行之间的任意行数),并将连接的结果输出到一个新列中。
到目前为止,连接和创建新列的工作都正常。然而,连接的结果也会输出到其他一些包含我需要的信息的列中,替换掉原有的数据。
有没有什么办法可以解决这个问题?
Sub ConcatenateSelectedColumns()
Dim SelectedRange As Range
Dim NewColumn As Range
Dim Cell As Range
Dim ConcatenatedValue As String
' Set the range of selected columns
Set SelectedRange = Selection
' Insert a new column to the right of the selected range
SelectedRange.Columns(SelectedRange.Columns.Count).Offset(, 1).EntireColumn.Insert
' Set the header for the new column
SelectedRange.Offset(, SelectedRange.Columns.Count).Value = "New Column"
' Loop through each row in the selected range
For Each Cell In SelectedRange.Rows
ConcatenatedValue = ""
For Each SubCell In Cell.Cells
ConcatenatedValue = ConcatenatedValue & SubCell.Value
Next SubCell
Cell.Offset(0, SelectedRange.Columns.Count).Value = ConcatenatedValue
Next Cell
End Sub
进程:
- 设置变量
- 为新列腾出空间,并将其插入表中,然后将其重命名。
- 对所选列范围中的每一行开始循环。
- 在每一行的开始处,将“concatenatedvalue”变量重置为空字符串。
- 将每个单元格的值追加到ConcatenatedValue中以进行连接。
- 将连接后的值放入当前行的新列中。
我认为问题出在最后一步,只是不确定如何解决。
解决方案
请尝试。
Option Explicit
Sub ConcatenateSelectedColumns()
Dim ColIndex As Long
Dim rngRow As Range
Dim Cell As Range
Dim ConcatenatedValue As String
' Check if a range is selected
If Not TypeName(Selection) = "Range" Then
MsgBox "Please select the columns you want to concatenate.", vbExclamation
Exit Sub
End If
' Add a new column to the right of the selected columns
With Selection
ColIndex = .Cells(1).Offset(0, .Columns.Count).Column
Columns(ColIndex).Insert
Cells(1, ColIndex).Value = "NewColumn"
' Loop through selected cells
For Each rngRow In .Rows
' Stop at the blank row if whole column(s) are selected
If Application.CountA(rngRow) = 0 Then Exit For
ConcatenatedValue = ""
For Each Cell In rngRow.Cells
' Concatenate values from selected columns
ConcatenatedValue = ConcatenatedValue & Cell.Value
Next Cell
Cells(rngRow.Row, ColIndex) = ConcatenatedValue
Next rngRow
End With
End Sub