excel 需要修改列连接脚本以仅连接选定的列,并使用逗号分隔连接的列

vpfxa7rd  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(123)

我需要这个代码:

Sub ConcatColumns()

   Do While ActiveCell <> "" 

      ActiveCell.Offset(0, 1).FormulaR1C1 = _
         ActiveCell.Offset(0, -1) & " " & ActiveCell.Offset(0, 0)

      ActiveCell.Offset(1, 0).Select
   Loop

End Sub

字符串
我需要修改它,使它不仅可以连接两列,而且可以连接多达4列,并且可以选择要连接的列。我还需要用逗号分隔连接的文本,因为这是Excel,我想知道如果其中一列是日期,是否有方法可以添加一些格式?
例如,我必须手动使用这个公式来确保我的日期在使用TEXTJOIN时格式为mm/dd/yyyy:

=TEXTJOIN(",",TRUE,IF(I4="","",(TEXT(I4,"mm/dd/yyyy"))),IF(J4="","",(TEXT(J4,"mm/dd/yyyy"))),IF(K4="","",(TEXT(K4,"mm/dd/yyyy"))))


我的数据是这样的:
原始数据
x1c 0d1x的数据
这可以继续与多达5-10个其他套的身份证的日期。
这是我需要的结果,也是我现在必须用=TEXTJOIN做的事情:



正如你所看到的日期不过来格式化,即使当我尝试这样做的时间,所以我必须添加一些=文本格式与公式,我上面粘贴。
提前感谢!

kiayqfof

kiayqfof1#

这里有一种方法。它将按照单元格/区域的选择顺序连接选择单元格内容(幸运的是,Excel在您进行多区域选择时会跟踪此操作)。结果将显示在最后选择的单元格中。

'When multiple cells in a row are selected, join the values from those cells with a comma,
'   and place the result in the last-selected cell
Sub JoinCells()
    Dim sel As Range, area As Range, c As Range, cDest As Range
    Dim addr As String, txt As String, sep As String, v

    Set sel = Selection

    'check that at least 3 cells are in the same row are selected...
    If sel.EntireRow.Cells.CountLarge > Rows(1).Count Or sel.Cells.Count < 3 Then
        MsgBox "Select at least 3 cells on the same row.", vbExclamation
        Exit Sub
    End If
    
    Do While Application.CountA(sel) > 0           'while any data in selected cells
        Set cDest = sel.Areas(sel.Areas.Count)     'last area selected
        Set cDest = cDest.Cells(cDest.Cells.Count) 'the last cell in that area is where the result goes
        addr = cDest.Address
        txt = ""    'reset result
        sep = ""    'reset separator
        For Each area In sel.Areas         'loop selected areas
            For Each c In area.Cells       'then cells within areas
                If c.Address <> addr Then  'not the "result" cell?
                    v = c.Value
                    If Len(v) > 0 Then     'any value to add?
                        txt = txt & sep & IIf(IsDate(v), Format(v, "mm/dd/yyyy"), v)
                        sep = ","          'add separator after first value
                    End If
                End If
            Next c
        Next area
        cDest.Value = txt       'populate the last selected cell
        Set sel = sel.Offset(1) 'next row down
    Loop
    
End Sub

字符串
范例:第3行的单元格是在按住Ctrl键的同时按显示的顺序选择的。确保最后选择一个空单元格作为结果的目标。

**注意:**只要下面的行中有内容,宏就会逐步向下遍历,因此只选择要处理的数据的第一行上的单元格。

x1c 0d1x的数据
测试结果:


相关问题