arrays - Excel 2010 VBA - 按逗号分割字符串,跳过空白结果

标签 arrays vba excel delimited

我使用以下代码来分割一列逗号分隔的列表,并返回新行中的每个条目:

Sub SliceNDice()
    '
    ' Splits the locations cells according to commas and pushes to new rows
    ' Code courtesy of brettdj (http://stackoverflow.com/questions/8560718/split-comma-separated-entries-to-new-rows)
    '
    Dim objRegex As Object
    Dim x
    Dim Y
    Dim lngRow As Long
    Dim lngCnt As Long
    Dim tempArr() As String
    Dim strArr
    Set objRegex = CreateObject("vbscript.regexp")

    objRegex.Pattern = "^\s+(.+?)$"
     'Define the range to be analysed
    x = Range([a1], Cells(Rows.Count, "c").End(xlUp)).Value2
    ReDim Y(1 To 3, 1 To 1000)
    For lngRow = 1 To UBound(x, 1)
         'Split each string by ","
        tempArr = Split(x(lngRow, 3), ",")
        For Each strArr In tempArr
            lngCnt = lngCnt + 1
             'Add another 1000 records to resorted array every 1000 records
            If lngCnt Mod 1000 = 0 Then ReDim Preserve Y(1 To 3, 1 To lngCnt + 1000)
            Y(1, lngCnt) = x(lngRow, 1)
            Y(2, lngCnt) = x(lngRow, 2)
            Y(3, lngCnt) = objRegex.Replace(strArr, "$1")
        Next
    Next lngRow
     'Dump the re-ordered range to columns E:G
    [e1].Resize(lngCnt, 3).Value2 = Application.Transpose(Y)

End Sub

虽然这段代码工作得很好,但它有一个致命的缺陷,即 C 列单元格中的任何双逗号都会导致空白单元格被推送到 G 列中的新行。

有谁知道如何编辑代码,以便它不会在 G 列中创建带有空单元格的新行,而是跳过它们并在其位置输入下一行,就好像多余的逗号根本不包含在 C 列中一样?

最佳答案

只需测试 strArr 的字符串长度,作为 For Each strArr In tempArr 循环内的第一个操作。

For Each strArr In tempArr
    If CBool(Len(strArr)) Then
        lngCnt = lngCnt + 1
         'Add another 1000 records to resorted array every 1000 records
        If lngCnt Mod 1000 = 0 Then ReDim Preserve Y(1 To 3, 1 To lngCnt + 1000)
        Y(1, lngCnt) = x(lngRow, 1)
        Y(2, lngCnt) = x(lngRow, 2)
        Y(3, lngCnt) = objRegex.Replace(strArr, "$1")
    End If
Next strArr

关于arrays - Excel 2010 VBA - 按逗号分割字符串,跳过空白结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35422738/

相关文章:

python - 如何从数组数组中创建一个 numpy 数组?

PHP - 检查数组索引是否存在或为空

vba - Microsoft Excel – 如何将每 n 行的单元格复制到不同的工作表

vba - 如何遍历一个范围并用值填充另一个工作表的单元格?

excel - 为什么无法将 Worksheets 对象变量初始化为 Worksheets 集合?

c# - 使用 Wrapper 对象正确清理 excel interop 对象

mysql - 如何在 JSON 数组中创建 JSON 数组

php - 将项目添加到关联数组

excel - 从托管的 HP 质量中心导出错误跟踪数据的最佳方式是什么?

excel - 根据当前年份和月份查找文本字符串 yyyymm