多个单元格中的VBA代码

时间:2013-08-09 13:48:37

标签: excel vba excel-vba

我使用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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)中写下,你的代码会得到相同的结果