1

我对使用 VBA 比较陌生。我有这段代码可以读取范围内的一组数据并将数据连接到一个单元格中。我有大量需要运行此代码的单元格。有人可以帮我循环它,所以当代码完成一个范围时,它会向下移动下一个单元格并从下一个范围开始?

Sub ConcatenateAll()
    Dim x As String, y As String, rng As Range, cell As Range

    With ActiveSheet
        Set rng = .Range("AT1:CB20")
        For Each cell In rng
            If cell.Value <> "" Then
                x = x & cell.Value & "; "
            End If
        Next
        .Range("AK1").Value = Left(x, Len(x) - 2)
    End With
End Sub
4

2 回答 2

0

我能想到的最好方法是将参数传递给ConcatenateAll过程,然后提及要连接的所有范围。例如,我ConcatenateAll()Sample()

我还冒昧地稍微修改了您的代码。

Sub Sample()
    With ActiveSheet
        ConcatenateAll .Range("AT1:CB20"), .Range("AK1")
        ConcatenateAll .Range("AT31:CB50"), .Range("AK2")
    End With
End Sub

Sub ConcatenateAll(rngInput As Range, rngOutput As Range)
    Dim x As String, cell As Range

    For Each cell In rngInput
        If Len(Trim(cell.Value)) <> 0 Then
            If x = "" Then
                x = cell.Value
            Else
                x = x & "; " & cell.Value
            End If
        End If
    Next

    rngOutput.Value = x
End Sub

跟进

AT1:CB20, AT21:CB40, AT41:CB60, AT61:CB80 我希望结果显示在 AK1, AK2, AK3, AK4 等直到范围结束 – user2668126 4 分钟前

试试这个代码。由于存在趋势,因此循环遍历范围变得更容易。

Option Explicit

Sub Sample()
    Dim r1 As Long, r2 As Long, i As Long

    r2 = 20: i = 1

    With ActiveSheet
        For r1 = 1 To 2001 Step 20
            ConcatenateAll .Range("AT" & r1 & ":CB" & r2), .Range("AK" & i)
            r2 = r2 + 20: i = i + 1
        Next
    End With
End Sub

Sub ConcatenateAll(rngInput As Range, rngOutput As Range)
    Dim x As String, cell As Range

    For Each cell In rngInput
        If Len(Trim(cell.Value)) <> 0 Then
            If x = "" Then
                x = cell.Value
            Else
                x = x & "; " & cell.Value
            End If
        End If
    Next

    rngOutput.Value = x
End Sub
于 2013-08-09T14:12:49.680 回答
0

由于您试图在单元格中显示输出,我认为最好的方法是编写一个自定义 VBA 函数,然后将其用作 Excel 工作表函数为此,首先您需要在VBA模块:

Public Function concat(values As Variant)

   Dim val As Variant, aux As String

   For Each val In values
       If val <> "" Then aux = aux & val & "; "
   Next val

   If Len(aux) > 2 Then aux = Left(aux, Len(aux) - 2)
   concat = aux

End Function

然后您可以将此函数用作工作表函数,例如您可以在单元格中写入,AK1 =concat(AT1:CB20)您将获得相同的代码结果

于 2013-08-09T14:14:07.457 回答