如何从单元格中提取前n个字符并将其复制到新的工作表中

时间:2019-01-14 14:08:42

标签: vba copy paste

我想将前两个单词提取到一个单元格中,将第三个单词提取到另一个单元格中,它们应该在新的工作表中。示例:

在Sheet1中,单元格A1'xxx-xx-xxx'

在Sheet2中,应该是这样的:

单元格A1:“ xxx-xx” 单元格A2:“ xxx”

如何使用VBA做到这一点?

任何帮助将不胜感激

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用VBA的“拆分”方法。

Sub SplitCell()

    getString = Sheets("Sheet1").Cells(1, 1).Value2
    splitString = Split(getString, "-")

    Sheets("Sheet2").Cells(1, 1) = splitString(0) & "-" & splitString(1)
    Sheets("Sheet2").Cells(2, 1) = splitString(2)

End Sub

答案 1 :(得分:0)

三分之二

Sub TwoOutOfThree()

    Const cSheet1 As Variant = "Sheet1"   ' Source Worksheet Name/Index
    Const cSheet2 As Variant = "Sheet2"   ' Target Worksheet Name/Index
    Const cCell As String = "A1"          ' Source/Target Cell Range
    Const cDel As String = "-"            ' Delimiter

    Dim vnt As Variant  ' Source Array

    With ThisWorkbook.Worksheets(cSheet1)
        ' Split Source Cell Range into Source Array.
        vnt = Split(.Range(cCell), cDel)
    End With

    With ThisWorkbook.Worksheets(cSheet2)
        ' Write first two words to first cell.
        .Range(cCell) = vnt(0) & cDel & vnt(1)
        ' Write third word to second cell.
        .Range(cCell).Offset(0, 1) = vnt(2)
    End With

End Sub