更新*
我是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列: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
谢谢你的帮助
这应该做你想要的。我使用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