级联代码不按预期工作

我在Excel VBA中编写了一个代码,用于将连续的值连接到连续的7列。 我注意到,如果我在前六列中input相同的值,我会得到没有^的输出。 这不会发生,如果我填写到第7或第5列。代码如下:

Private Sub CommandButton21_Click() Cells(2, 1).Select Dim stri As String, eaid_1 As String, eaid_2 As String, eaid_3 As String, _ eaid_4 As String, eaid_5 As String, eaid_6 As String, eaid_7 As String Do Until Selection.Value = "" eaid_1 = Selection.Value eaid_2 = Selection.Offset(0, 1).Value eaid_3 = Selection.Offset(0, 2).Value eaid_4 = Selection.Offset(0, 3).Value eaid_5 = Selection.Offset(0, 4).Value eaid_6 = Selection.Offset(0, 5).Value eaid_7 = Selection.Offset(0, 6).Value stri = eaid_1 & "^" & eaid_2 & "^" & eaid_3 & "^" & eaid_4 & "^" & eaid_5 _ & "^" & eaid_6 & "^" & eaid_7 Selection.Offset(0, 8).Value = stri Selection.Offset(1, 0).Select Loop Cells(2, 9).Select Dim x As String, y As String, z As String Do Until Selection.Value = "" x = Selection.Value y = Right(x, 6) z = Replace(y, "^", "") x = Replace(x, y, z) Selection.Offset(0, 0).Value = x Selection.Offset(1, 0).Select Loop End Sub 

 Private Sub CommandButton21_Click() Const NUM_COLS As Long = 7 Dim c As Range, rng As Range Set c = Cells(2, 1) Do While c.Value <> "" Set rng = c.Resize(1, Application.CountA(c.Resize(1, NUM_COLS))) c.Offset(0, NUM_COLS).Value = _ Join(Application.Transpose(Application.Transpose(rng.Value)), "^") Set c = c.Offset(1, 0) Loop End Sub 

一些解释:

  • 您应该避免使用Select / Activate来处理范围,而是使用Rangevariables(如上面的c
  • DoWhile...Loop从A2开始并继续,直到c为空
  • rngvariables表示一个Range对象,从c开始,向右延伸到与所有值相同的单元格(最多7个单元格)。 CountA工作表函数用于计算值的数量, Resize创build所需大小的范围。
  • 重复的Application.Transpose创build一个二维数组中的一维数组,生成rng.Value 。 不要问我解释到底为什么工作;-)
  • 最后, Join接受一维数组,并返回一个单一的string,input数组的每个元素连接到下一个并由第二个参数(“^”)分隔

下面的代码将“ CONCATENATE ”每一行(其中列A有数据),并检查每一行最后一列的数据,然后将它们组合在一起(每个数组元素之间添加“ ^ ”)。 目前它将结果string放在列I中 ,就像在你的文章中)。

你的第二个循环的目的是什么? 你的最终结果应该是什么样子?

 Private Sub CommandButton21_Click() Dim Rng As Range Dim stri As String Dim eaid() As Variant Dim lRow As Long Dim i As Long Dim LastColumn As Long ' start from Cell A2 lRow = 2 Do Until Range("A" & lRow).Value = "" ' get the last column with data in current row LastColumn = Cells(lRow, Columns.Count).End(xlToLeft).Column ReDim eaid(1 To LastColumn) Set Rng = Range("A" & lRow) ' read all Range values to one-dimension array using Transpose eaid = Application.Transpose(Application.Transpose(Rng.Resize(1, LastColumn).Value)) ' read all array elements to String For i = LBound(eaid) To UBound(eaid) If i = LBound(eaid) Then stri = stri & eaid(i) Else stri = stri & "^" & eaid(i) End If Next i Rng.Offset(0, 8).Value = stri stri = "" lRow = lRow + 1 Loop End Sub