如果末尾只有一个值要连接,则在结果末尾不保留逗号 [duplicate]

Leave no trailing comma at the end of the result if there's only one value at the end to be concatenated [duplicate]

提问人:user16201107 提问时间:11/14/2023 最后编辑:user16201107 更新时间:11/14/2023 访问量:107

问:

我当前的代码采用选定的列并将它们连接起来,用逗号分隔每个值,在工作表的右侧插入一列。但是,每当有一行只有一个值时,它就会在末尾留下一个尾随逗号。如果有多个值,它不会在结果末尾留下逗号,只有当有一个值时,例如:

多个值:“text1,text2,text3” 单个值:“text1”,

我需要什么:“text1”

法典:

    Sub ConcatenateSelectedRanges()
    Dim selectedRange As Range
    Dim cell As Range
    Dim concatenatedString As String
    Dim resultColumn As Range
    Dim lastColumn As Long
    Dim rowIndex As Long
    Dim area As Range
    Dim isDateResponse As VbMsgBoxResult
    
    ' Check if a range is selected
    On Error Resume Next
    Set selectedRange = Selection
    On Error GoTo 0
    
    If selectedRange Is Nothing Then
        MsgBox "Please select a range to concatenate.", vbExclamation
        Exit Sub
    End If
    
    ' Prompt the user if the content in the selected range is a date
    isDateResponse = MsgBox("Is the content in the selected range a date?" & vbCrLf & _
                            "Selected Range: " & selectedRange.Address, vbYesNo + vbQuestion, "Date Check")
    
    If isDateResponse = vbCancel Then
        Exit Sub ' Exit if the user cancels the prompt
    End If
    
    ' Find the first available empty column to the right of the selected range
    On Error Resume Next
    Set resultColumn = selectedRange.Offset(0, selectedRange.Columns.Count + 1).Resize(, 1)
    On Error GoTo 0
    
    If resultColumn Is Nothing Then
        ' If no available empty column is found, insert a new column at the end
        lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
        Set resultColumn = Columns(lastColumn + 1).EntireColumn
        resultColumn.Insert
        ' Resize the resultColumn to match the height of the selected range
        Set resultColumn = resultColumn.Resize(selectedRange.Rows.Count)
    End If
    
    ' Loop through each area within the selection
    For Each area In selectedRange.Areas
        ' Loop through each row in the current area
        For rowIndex = 1 To area.Rows.Count
            ' Reset the concatenated string for each row
            concatenatedString = ""
            
            ' Loop through each cell in the current row
            For Each cell In area.Rows(rowIndex).Cells
                If cell.Value <> "" Then ' Ignore blank cells
                    If isDateResponse = vbYes Then
                        ' Append the formatted date to the string
                        concatenatedString = concatenatedString & Format(cell.Value, "mm/dd/yyyy") & ","
                    Else
                        ' Append the cell value to the string
                        concatenatedString = concatenatedString & cell.Value & ","
                    End If
                End If
            Next cell
            
            ' Remove the trailing comma if there's only one non-empty cell
            If Len(concatenatedString) > 0 Then
                If Len(concatenatedString) > 1 Then ' Check if there's more than one character
                    If Right(concatenatedString, 1) = "," Then
                        concatenatedString = Left(concatenatedString, Len(concatenatedString) - 1)
                    End If
                End If
            End If
            
            ' Display the concatenated string in the corresponding row of the new column
            resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value = _
                resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value & IIf(resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value = "", "", ",") & concatenatedString
        Next rowIndex
    Next area
End Sub
Excel VBA 文本 串联

评论

3赞 Solar Mike 11/14/2023
测试最后一个字符是否为逗号,如果为 true,则将其删除。
0赞 JNevill 11/14/2023
或者,使用数组来收集值(在每次迭代中增加它并添加新项),然后使用数组来获取连接列表。redim preservejoin
0赞 user16201107 11/14/2023
我需要逗号来分隔值,只是不在结果的末尾。如果最后只有一个值,则不应包含逗号。
0赞 Tim Williams 11/14/2023
您可以遵循我在回答您上一个问题时使用的模式。对逗号使用单独的变量,并且仅在添加第一项后填充它。
0赞 CDP1802 11/14/2023
所选范围是否有不连续的列,即 A:B 和 D?

答:

0赞 rotabor 11/14/2023 #1

由于结果字符串由文本后跟逗号组成,因此根据此代码

                        concatenatedString = concatenatedString & Format(cell.Value, "mm/dd/yyyy") & ","
                    Else
                        ' Append the cell value to the string
                        concatenatedString = concatenatedString & cell.Value & ","

您只需要检查字符串的长度是否大于零并删除尾随逗号!

            ' Remove the trailing comma if there's only one non-empty cell
            If Len(concatenatedString) > 0 Then
                        concatenatedString = Left(concatenatedString, Len(concatenatedString) - 1)
            End If

别紧张!

尾随逗号的根本原因如下:

            resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value = _
                resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value & IIf(resultColumn.Cells(rowIndex + area.Rows(1).Row - 1, 1).Value = "", "", ",") & concatenatedString

我不想深入研究它。只需应用额外的检查:

            resultColumn.Cells(rowIndex + area.Row - 1, 1) = _
                resultColumn.Cells(rowIndex + area.Row - 1, 1) _
                & IIf(resultColumn.Cells(rowIndex + area.Row - 1, 1) = "" Or Len(concatenatedString) = 0, "", ",") _
                & concatenatedString

评论

0赞 user16201107 11/14/2023
我用你的替换了它,它继续与某些人一起工作,但不能与其他人一起使用:(imgur.com/jvcxXdC也许这是其中一个循环中的问题?只是不能把我的手指放在上面。不知道这是否与最后一个字符是字母或数字有关。
0赞 rotabor 11/14/2023
添加了解决方案。
0赞 user16201107 11/14/2023
我只是仔细检查了这一点,它停止将第二列的数据添加到第 31 行的串联结果中。它只是添加第一列。
0赞 rotabor 11/14/2023
:-)这不是你的问题......
0赞 rotabor 11/14/2023
若要调试代码,请放置“Debug.Print 区域。Rows.Count“添加到”For rowIndex = 1 To area.Rows.Count“,运行代码,然后在”即时“窗口(VB 编辑器,Ctrl+G)中检查结果。将您的期望值与实际处理的行数进行比较。