VBA - 根据长度将单元格字符串分成单个单元格
VBA - Breaking a cell string into individual cells based on length
我有一个包含不同长度字符串的单元格。我想将它们拆分成长度为 3 个字符的单个单元格。
具有 ABCCBA
的单元格应该在 2 个不同的单元格中结束 ABC
CBA
。
虽然带有 ABCDABCDAB
的单元格应该在 4 个不同的单元格中结束 ABC
DAB
CDA
B
。
有什么方便的方法吗?
我在看
' Finding number of cells
Segments = WorksheetFunction.RoundUp(Len(Range("A1").Value) / 3, 0)
' Split base on character length
For n = 1 to Segments
Cells(2, n) = Range("A1").Characters(n, 3)
Next n
但是好像不行。
如果您熟悉公式,假设您的数据位于单元格 A2 中,并且您希望在单元格 B2 及右侧实现公式。
B2 中的公式:
=MID($A2,(COLUMNS($B:B2)-1)*3+1,3)
根据需要将其复制下来。
一个简单的宏,用于将字符串拆分为 3 个字母的字符串并写入数据范围旁边的列
Sub Split()
Dim Checkcol As Integer
Dim currentRowValue As String
Dim rowCount As Integer
Dim splitval As Integer
Dim i As Integer, j As Integer
Checkcol = 1 'Denotes A column
rowCount = Cells(Rows.Count, Checkcol).End(xlUp).Row
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, Checkcol).Value
splitval = Int(Len(currentRowValue) / 3) + 1 'Find the number of 3 letter strings
j = 0
For i = 1 To splitval 'Loop through each value and write in next columns
j = (i - 1) * 3 + 1
Cells(currentRow, Checkcol + i).Value = Mid(currentRowValue, j, 3)
Next
Next
End Sub
我有一个包含不同长度字符串的单元格。我想将它们拆分成长度为 3 个字符的单个单元格。
具有 ABCCBA
的单元格应该在 2 个不同的单元格中结束 ABC
CBA
。
虽然带有 ABCDABCDAB
的单元格应该在 4 个不同的单元格中结束 ABC
DAB
CDA
B
。
有什么方便的方法吗?
我在看
' Finding number of cells
Segments = WorksheetFunction.RoundUp(Len(Range("A1").Value) / 3, 0)
' Split base on character length
For n = 1 to Segments
Cells(2, n) = Range("A1").Characters(n, 3)
Next n
但是好像不行。
如果您熟悉公式,假设您的数据位于单元格 A2 中,并且您希望在单元格 B2 及右侧实现公式。
B2 中的公式:
=MID($A2,(COLUMNS($B:B2)-1)*3+1,3)
根据需要将其复制下来。
一个简单的宏,用于将字符串拆分为 3 个字母的字符串并写入数据范围旁边的列
Sub Split()
Dim Checkcol As Integer
Dim currentRowValue As String
Dim rowCount As Integer
Dim splitval As Integer
Dim i As Integer, j As Integer
Checkcol = 1 'Denotes A column
rowCount = Cells(Rows.Count, Checkcol).End(xlUp).Row
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, Checkcol).Value
splitval = Int(Len(currentRowValue) / 3) + 1 'Find the number of 3 letter strings
j = 0
For i = 1 To splitval 'Loop through each value and write in next columns
j = (i - 1) * 3 + 1
Cells(currentRow, Checkcol + i).Value = Mid(currentRowValue, j, 3)
Next
Next
End Sub