VBA拆分细胞并仅粘贴特定细胞

问题描述 投票:0回答:1

更新*

我是VBA新手所以非常感谢帮助

我有一张表格,我在这个结构中的A列内容:

A1:列标题A2:044000 randomwordx(数字和随机字之间有3个空格) A3:056789 randomwordy(数字和随机字之间有3个空格)A4:

兄弟:a 框架:A.randomords简介:

A8:600000 randomwordz(数字和随机字之间有3个空格) A9:654124随机字(数字和随机字之间有3个空格)

A列中数字和随机字之间的分隔符总是3x空格

我想做的是以下内容:

转到A列 - 选择以6位数字开头的所有单元格

  • 将这些细胞分开并粘贴到C和D列中
  • C列应仅包含起始编号,删除任何前导零(如果单元格A2具有例如044000,则单元格C2应为44000)
  • 列D应仅包含在列A的起始编号之后出现的文本(在此示例中,D2应为“randomwordx”)
  • A列中的空白或不以6位数字开头的单元格不应粘贴在C和D列中(在此示例中A4,A5,A6,A7不应粘贴到C和D列中)

所以看起来应该是这样的

C列:C1:Columnheader

C2:44000

S 3:56789

S 4:60000

C5:653124

D栏:

D1:Columnheader

D2:randomwordx

D3:randomwordy

D4:randomwordz

D5:randomwords

我设法得到这么远,所以帮助将不胜感激

Option Explicit

Sub Splitcolumn() 
Dim mrg As Range
Dim LastRow As Long
Dim r As Range
Dim splitted() As String

With Sheets("test")
    Set mrg = Sheets("test").Range("A4:A" & LastRow)
    For Each r In mrg 
        splitted = Split(r.Value, "   ") 
        r.Value = splitted(0)
        r.Offset(2, 3).Value = splitted(1) & "   " & splitted(2)
    Next r
End With
End Sub

我收到运行时错误1004

谢谢你的帮助

vba split delimiter
1个回答
0
投票

这应该做你想要的。我使用Portland Runner's answer to this post在我的VBA中设置RegEx引用并学习它的语法。我计算A列的最后一行,并使用带有那么多次迭代的for循环,而不是每个循环。 i变量设置为2以跳过第1行中的标题。

Sub SplitCol()
    'Set references to active workbook and sheet
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = wb.ActiveSheet

    'Create Regular Expression object and set up options
    Dim regEx As New RegExp
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        '[0-9] means that regex will check for all digits
        '{6} means that a minimum of 6 consecutive chars must meet the [0-9] criteria
        .pattern = "[0-9]{6}"
    End With

    'All .Methods and .Properties will belong to ws object due to With
    With ws
        'Determine how many rows to loop through
        Dim lastRowA As Long
        lastRowA = .Range("A" & .Rows.Count).End(xlUp).Row

        'Main loop
        Dim i As Integer
        For i = 2 To lastRowA
            'Make sure there is a value in the cell or code will error out
            If Cells(i, 1).Value <> "" Then
                'Test regex of cell
                If regEx.Test(Split(Cells(i, 1).Value, "   ")(0)) Then
                    'If regex was true, set 3rd column (C) equal to numbers and
                    '4th column (D) equal everything else
                    Cells(i, 3).Value = Split(Cells(i, 1).Value, "   ")(0)
                    Cells(i, 4).Value = Split(Cells(i, 1).Value, "   ")(1)
                End If
            End If
        Next
    End With

    'Release regEx object to reduce memory usage
    Set regEx = Nothing

End Sub

This is what the code should make the sheet look like.

© www.soinside.com 2019 - 2024. All rights reserved.