具有回车的单元格的单元格范围

时间:2012-04-20 14:41:53

标签: excel excel-vba vba

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

我想我需要:

  • 在列
  • 中找到第一个带有值的单元格
  • 验证下一行是否为空
  • 找到范围内的最后一个单元格
  • 在范围
  • 上执行“操作”

Start

enter image description here

2 个答案:

答案 0 :(得分:2)

跟进我的评论。这是实现你想要的一种非常简单的方法。

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

答案 1 :(得分:1)

在工作表级代码的上下文中,以下内容将起作用。第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