使用Excel VBA将列文本拆分为相邻列

时间:2016-05-04 21:40:18

标签: excel vba excel-vba

我有一张Excel表格,其中的栏目包含" Hello there 2005 A"我想在两列之间拆分此文本,其中一列包含' Hello there 2005'另一种说法是' A'。

我在VBA中尝试过分割功能,但是我无法让它在整个列中循环,甚至可能会出现一个分隔符,它会在字母“A' A'”之前完全分开。

结果应如下所示:

Results

2 个答案:

答案 0 :(得分:0)

Instr(cellValue,“”) 会给你第一个空间的位置

firstPos = instr(cellValue," ")  ' first space
secondPos = instr(firstPos + 1, cellValue, " ") ' second space

等。

后跟midreplace

secondColumnValue = mid(cellValue, thirdPos + 1)
firstColumnValue = replace(cellValue, secondColumnValue, "")

答案 1 :(得分:0)

试试这个

Option Explicit

Sub main()
Dim cell As Range
Dim strng As Variant
Dim rightStrng As String
Dim i As Long

With Worksheets("multimanager") '<== change it as per your needs
    For Each cell In .Columns("A").SpecialCells(xlCellTypeConstants, xlTextValues) 'assuming that "column containing texts" is column "A"
        strng = Split(cell)
        rightStrng = ""
        i = UBound(strng)
        Do While Not IsNumeric(strng(i)) And i > 0
            rightStrng = strng(i) & " " & rightStrng
            i = i - 1
        Loop
        If IsNumeric(strng(i)) Then
            rightStrng = Application.WorksheetFunction.Trim(rightStrng)
            cell.Offset(, 2) = rightStrng
            cell.Offset(, 1) = Left(cell.Value, IIf(rightStrng <> "", InStrRev(cell.Value, rightStrng) - 2, Len(cell.Value)))
        End If
    Next cell

End With

End Sub