Vba连接多列直到为空

时间:2019-06-14 20:28:07

标签: excel vba concatenation multiple-columns

我正在尝试创建一个宏以连接多个列,直到找到一个空单元格为止,当它发现应该将连接的文本放在第一个单元格中时。 The image显示了它应该如何工作。在此示例中,我具有从B到M的值,但是它可以变化。谢谢您的帮助和时间!

2 个答案:

答案 0 :(得分:0)

尝试一下,请参阅注释以获取更多详细信息:

Option Explicit

Sub concatenateValues()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet Name") '
Dim lRow As Long: lRow = ws.Cells(Rows.Count, 2).End(xlUp).Row 'get last row at column B
Dim lCol As Long: lCol = ws.Cells(1, Column.Count).End(xlToLeft).Column 'get last column at row 1, assuming you have at least headers

Dim arrData As Variant: arrData = ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)) 'declare and allocate your data to an array

Dim R As Long, C As Long

For R = LBound(arrData) + 1 To UBound(arrData) 'for each row in your data, start at row 2
    For C = LBound(arrData, 2) + 1 To UBound(arrData, 2) 'for each column in your data, start at column 2
        arrData(R, 1) = arrData(R, 1) & arrData(R, C) 'concatenate the values
    Next C
Next R

ws.Range(ws.Cells(1, 1), ws.Cells(lRow, lCol)) = arrData 'put the values back into the sheet

End Sub

答案 1 :(得分:0)

这是VBA解决方案。我以为第二列中总会有一个值。

Sub Concat()
Dim i As Integer, Sht As Worksheet, Str As String
i = 3
Set Sht = ThisWorkbook.Sheets(1) 'Change this to whatever sheet you're using
Str = Sht.Cells(1, 2).Value
Do Until Sht.Cells(1, i).Value = ""
    Str = Str & "-" & Sht.Cells(1, i).Value
    i = i + 1
Loop
Sht.Cells(1, 1).Value = Str
End Sub