【问题标题】:Microsoft Excel VBA text split tweakMicrosoft Excel VBA 文本拆分调整
【发布时间】:2015-07-23 20:57:42
【问题描述】:

我有一个 Excel 工作表,当它被扫描(通过即插即用条形码扫描仪)到右侧的第一列时,它使用宏将文本字符串拆分为使用空格字符作为分隔符的第一列。 Excel 工作表的示例图片,后跟 Excel 宏。

Sub textsplit(rng As Range)
    Dim c As Range, Arr

    For Each c In rng.Cells
        If Len(c.Value) > 0 Then
            Arr = Split(c.Value, " ")
            c.Offset(0, 1).Resize(1, UBound(Arr) + 1).Value = Arr
        End If
    Next c
End Sub

现在所有这些都可以完美运行,但是我需要对此进行一些调整。 我希望宏跳过第一个序列(“CNA1234567”)之后的列并将其留空。我该如何调整这段代码来做到这一点?

【问题讨论】:

  • 您是说,根据您的图表,您希望“4512517”进入“PA 编号”列。如果没有,您能否再张贴一张它应该是什么样子的图片?
  • "在第一个序列之后跳过列..." after 描述是否意味着您希望材料编号留空?
  • @LimaNightHawk 好问题。在我在下面编写的代码中,我假设该问题的答案是“是”,但你说得对,它并不是很清楚。

标签: vba excel tweak


【解决方案1】:

这个方法更明确一点,会给你所有你想要的控制。

Sub textsplit(rng As Range)
    Dim c As Range
    Dim r As Long
    Dim Arr As Variant

    For Each c In rng.Cells
        If Len(c.Value) > 0 Then

            r = c.Row

            Arr = Split(c.Value, " ")
            With Sheet1
                .Cells(r, 2).Value = Arr(0)
               '.Cells(r, 3).Value = <--- skipped 
                .Cells(r, 4).Value = Arr(1)
                .Cells(r, 5).Value = Arr(2)
                .Cells(r, 6).Value = Arr(3)
                .Cells(r, 7).Value = Arr(4)
                .Cells(r, 8).Value = Arr(5)
           End With
        End If
    Next c
End Sub

【讨论】:

  • 谢谢 Lima,它就像 John 的解决方案一样工作,但是如果我想要跳过每一个更改的行,它对用户来说更加友好。你摇滚。
【解决方案2】:

这行得通:

Sub textsplit(rng As Range)
    Dim c As Range, Arr As Variant
    Dim i As Long

    For Each c In rng.Cells
        If Len(c.Value) > 0 Then
            Arr = Split(c.Value, " ")
            For i = 0 To UBound(Arr)
                c.Offset(0, IIf(i > 0, i + 2, i + 1)).Value = Arr(i)
            Next i
        End If
    Next c
End Sub

如果rng 很大,您可以先关闭屏幕更新,然后再打开。

【讨论】:

  • 这完全符合我的需要。谢谢约翰!
【解决方案3】:

3无论该列的数字是多少,只需检查您是否不在其上。

Sub textsplit(rng As Range)
    Dim c As Range, Arr

    For Each c In rng.Cells
        If c.Column <> 3 Then
            If Len(c.Value) > 0 Then
                Arr = Split(c.Value, " ")
                c.Offset(0, 1).Resize(1, UBound(Arr) + 1).Value = Arr
            End If
        End if
    Next c
End Sub

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多