将单元格的范围转换为带有回车符的单元格

我正在通过我的第一本VBA书,并希望有人能指出我正确的方向。 我如何将一个行的范围转换成一个单元格与回车? 然后,我想对该列中的所有范围重复此操作。

我想我需要:

  • 在列中find第一个具有值的单元格
  • validation下一行不是空的
  • find范围中的最后一个单元格
  • 在范围上执行“操作”

开始

在这里输入图像描述

跟进我的意见。 这里是一个非常简单的方法来实现你想要的。

 Option Explicit '~~> You can use any delimiter that you want Const Delim = vbNewLine Sub Sample() Dim rngInput As Range, rngOutput As Range Application.ScreenUpdating = False Set rngInput = Range("A1:A5") '<~~ Input Range Set rngOutput = Range("B1") '<~~ Output Range Concatenate rngInput, rngOutput Application.ScreenUpdating = True End Sub Sub Concatenate(rng1 As Range, rng2 As Range) Dim cl As Range Dim strOutPut As String For Each cl In rng1 If strOutPut = "" Then strOutPut = cl.Value Else strOutPut = strOutPut & Delim & cl.Value End If Next rng2.Value = strOutPut End Sub 

在工作表级代码的上下文中,以下内容将起作用。 第2列是硬编码的,所以你可能想传入一个值或者修改它以适合你的需要。

 Dim rng As Range Set rng = Me.Columns(2) Dim row As Integer row = 1 ' Find first row with non-empty cell; bail out if first 100 rows empty If IsEmpty(Me.Cells(1, 2)) Then Do row = row + 1 Loop Until IsEmpty(Me.Cells(row, 2)) = False Or row = 101 End If If row = 101 Then Exit Sub ' We'll need to know the top row of the range later, so hold the value Dim firstRow As Integer firstRow = row ' Combine the text from each subsequent row until an empty cell is encountered Dim result As String Do If result <> "" Then result = result & vbNewLine result = result & Me.Cells(row, 2).Text row = row + 1 Loop Until IsEmpty(Me.Cells(row, 2)) ' Clear the content of the range Set rng = Me.Range(Me.Cells(firstRow, 2), Me.Cells(row, 2)) rng.Clear ' Set the text in the first cell Me.Cells(firstRow, 2).Value2 = result