Excel 用定界符连接可变长度行的宏

Excel Macro to Concatenate Rows of Variable Lengths with Delimiter

我正在开发一个工作表,用户可以填写该工作表以生成一个可以上传到 SAP 的文件。

工作表将生成单个条目的大量上传。用户将被要求为他们请求的每个行项目提供属性,这些属性可能会根据所做的选择而有所不同(即一行可能有 5 个属性,而下一行可能有 7 个)。

我想编写一个宏来查看每一行,从顶部开始,并仅连接非空白的属性列(在每个实例中由另外两列分隔)并在它们之间使用分隔符每个领域。

我已经能够使用通过 Microsoft 找到的一些代码来完成循环(见下文),但我无法弄清楚如何在列为空时停止连接然后移动到下一行。

Sub Submit()
Range("C2").Activate
Do While ActiveCell <> ""  

ActiveCell.Offset(0, 21).FormulaR1C1 = _
ActiveCell.Offset(0, 0) & "-" & ActiveCell.Offset(0, 3) & "-" & 

ActiveCell.Offset(0, 6) & "-" & ActiveCell.Offset(0, 9) & "-" & ActiveCell.Offset(0, 12) & "-" & ActiveCell.Offset(0, 15) & "-" & ActiveCell.Offset(0, 18)

ActiveCell.Offset(1, 0).Select

Loop
End Sub

现在,此代码将采用五个属性条目并留给我“1-2-3-4-5--”,而我真的希望它显示为“1-2-3-” 4-5".

关于我如何着手做这件事有什么想法吗?最终,我希望能够存储这些字符串并使用从原始工作簿复制的一些其他信息将它们填充到新工作簿中。

未测试:

Sub Submit()

Dim c As Range, c2 As Range, v as String


Set c = Range("C2")
Do While c.Value <> ""  

    Set c2 = c
    v = ""
    Do While c2.value <> ""
        v = v & IIf(v <> "", "-", "") & c2.value
        Set c2 = c2.offset(0, 3)
    Loop
    c.offset(0, 21).Value = v

    Set c = c.Offset(1, 0) 

Loop
End Sub

这是一个快速的回答,所以可能没有您想要的一切:

Public Function Submit(Target As Range) As String

    Dim sFinalOutput As String
    Dim rCell As Range

    'Cylce through each cell in your range.
    For Each rCell In Target

        'Look at the column number divided by 3 - if it's 0 then carry on.
        If rCell.Column Mod 3 = 0 Then
            If rCell.Value2 <> "" Then
                'Grab the value from the cell and add it to the final output.
                sFinalOutput = sFinalOutput & "-" & rCell.Value2
            End If
        End If
    Next rCell

    Submit = sFinalOutput

End Function

在公式中使用它,例如:=submit(C4:L4)