在VBA Excel中的2个特定列名之间连接N个列数

我试图连接2个特定列之间的选定范围。 我的第一个列名是“产品名称”(第一列是固定的),第二列是不固定的。 它可以是第3,第4,第5或N,该栏的名称是“价格”。 我想连接这两列之间的所有列。 我试了下面的代码。

Sub test() Cells(1, 1).Select j = 1 Do k = Cells(1, j).Value Cells(1, j).Select j = j + 1 Loop Until (k = "Product-name") c1 = j Do k = Cells(1, j).Value Cells(1, j).Select j = j + 1 Loop Until (k = "Price") c2 = j - 2 If (c2 > c1) Then 'I am doing something wrong here. Please let me know the correct syntax CONCATENATE(Range(Columns(c1), Columns(c2))) End If End Sub 

@nbayly是正确的,你不能连接这样的整个范围,即使你可以不把结果分配给任何东西。

这是一种使用不同技术来完成的方法。 testing数据如下所示:

在这里输入图像描述

确保将产品和价格的列或标题单元设置为已命名的范围。 这里是一个例子,如果你不确定我的意思:

在这里输入图像描述

现在运行这个代码:

 Sub concatTest() Dim wks As Worksheet Set wks = ActiveSheet Dim colStart As String, colEnd As String colStart = wks.Range("ProductName").Column colEnd = wks.Range("Price").Column Dim resultString As String Dim LastRow As Integer: LastRow = wks.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For eachRow = 2 To LastRow resultString = "" For y = colStart To colEnd resultString = resultString & wks.Cells(eachRow, y) Next y Debug.Print resultString Next eachRow End Sub 

结果在即时窗口中,您也可以将此数据放在某个列中:

在这里输入图像描述