在excel vba中拆分数字和文本

我在以下格式的excel中有一列:

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。 基本上把数字作为文本通过math运算,然后excel将其转换为数字。

感谢所有的帮助。 我有一个很好的解决scheme。

 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 

所以还在做这个。 请让我知道,如果出了什么事。 谢谢

正如Tim Williams所build议的,Splitfunction可能是最好的。 如果你不想使用VBA,你可以尝试内置函数Text to Columns。 根据分隔符等,这将产生3列: 在这里输入图像说明

在这里输入图像说明