我在Excel中按以下格式列在Excel VBA中的号码和文字:拆分
Column A
100 Test A
200 Test B
300 Test C
我想打开Excel并分别分裂数字和文本分成两列,比如:
Column A Column B
100 Test A
200 Test B
300 Test C
任何人都可以帮助我解决这个问题。
我在Excel中按以下格式列在Excel VBA中的号码和文字:拆分
Column A
100 Test A
200 Test B
300 Test C
我想打开Excel并分别分裂数字和文本分成两列,比如:
Column A Column B
100 Test A
200 Test B
300 Test C
任何人都可以帮助我解决这个问题。
我觉得你过于复杂的事情:
Option Explicit
Sub SplitCells()
Dim totRange As Range
Dim r As Range
Dim splitted() As String
Set totRange = Range("A1:A3")
For Each r In totRange
splitted = Split(r.Value, " ")
r.Value = splitted(0)
r.Offset(0, 1).Value = splitted(1) & " " & splitted(2)
Next r
End Sub
是的,这为我提供了相同的解决方案,并且使过程变得简单。谢谢 :) –
非VBA选项
对于塔B
=--left(A1,find(" ",A1)-1)
和C列
=right(A1,len(A1)-find(" ",A1))
根据需要复制这些内容。如果出于某种原因,您希望将该数字保留为文本而不是转换为数字,请从第一个等式中删除 - 。在方程末尾,将数字转换为数字的其他一些方法是+0或* 1。基本上把数字作为文本通过数学运算,并将excel转换为数字。
感谢您的帮助。我有一个很好的解决方案。
Private Sub SplitData()
Dim sourceSheetName As String
Dim sourceSheet As Worksheet
Dim lastRow As Long
Dim uboundMax As Integer
Dim result
On Error GoTo SplitterErr
sourceSheetName = "TestSheet"
If sourceSheetName = "" Then _
Exit Sub
Set sourceSheet = Worksheets(sourceSheetName)
With sourceSheet
lastRow = .Range(sourceColumnName & .Rows.Count).End(xlUp).Row
result = SplittedValues(data:=.Range(.Cells(1, sourceColumnName), _
.Cells(lastRow, sourceColumnName)), _
partsMaxLenght:=uboundMax)
If Not IsEmpty(result) Then
.Range(.Cells(1, sourceColumnName), _
.Cells(lastRow, uboundMax)).value = result
End If
End With
SplitterErr:
If Err.Number <> 0 Then _
MsgBox Err.Description, vbCritical
End Sub
Private Function SplittedValues(_
data As Range, _
ByRef partsMaxLenght As Integer) As Variant
Dim r As Integer
Dim parts As Variant
Dim values As Variant
Dim value As Variant
Dim splitted As Variant
If Not IsArray(data) Then
' data consists of one cell only
ReDim values(1 To 1, 1 To 1)
values(1, 1) = data.value
Else
values = data.value
End If
ReDim splitted(LBound(values) To UBound(values))
For r = LBound(values) To UBound(values)
value = values(r, 1)
If IsEmpty(value) Then
GoTo continue
End If
' Split always returns zero based array so parts is zero based array
parts = VBA.Split(value, delimiter)
splitted(r) = parts
If UBound(parts) + 1 > partsMaxLenght Then
partsMaxLenght = UBound(parts) + 1
End If
continue:
Next r
If partsMaxLenght = 0 Then
Exit Function
End If
Dim matrix As Variant
Dim c As Integer
ReDim matrix(LBound(splitted) To UBound(splitted), _
LBound(splitted) To partsMaxLenght)
For r = LBound(splitted) To UBound(splitted)
parts = splitted(r)
For c = 0 To UBound(parts)
matrix(r, c + 1) = parts(c)
Next c
Next r
SplittedValues = matrix
End Function
但这段代码的输出结果如下:
Column A Column B Column C
100 Test A
200 Test B
300 Test C
所以仍然是这方面的工作。如果出现问题,请告诉我。由于
可以使用(例如)'斯普利特(cellValue, “”,1)'你尝试过什么? –
@TimWilliams被分成2016年的功能? –
不,它是在VBA中,因为Office 2000我认为(Q用VBA标记) –