从excel中的字符串中提取日期,然后复制到新行中

时间:2018-10-10 20:58:08

标签: excel excel-vba excel-formula

如何从Microsoft Excel单元格的String中提取日期?我在单元格A上有以下信息

在单元格A2中,我有:360485 在单元格B2中(请注意:它在单个单元格中的环绕文本):

  10/7 - comment 1
  5/3/16 - comment 2
  3/21/16 comment 3
  1/26/16 - comment 4"

我想得到这样的东西

Col A    Col B      Col C
360485  10/7/16   - comment 1
360485  5/3/16    - comment 2
360485  3/21/16     comment 3
360485  1/26/16   - comment 4"

@JNevill,

A列中的数据:600537L 列B中的数据

6/21/17 - text comment 1 
951396-LH/RH-951554
10/27 - text comment 2
normal text
2/5/16 - text comment 3"

结果

 Col A    Col B                      Col C
600537L 6/21/2017             - text comment 1
600537L 951396-LH/RH-951554 
600537L 27-Oct               - text comment 2
600537L normal               text
600537L 2/5/2016             - text comment 3

2 个答案:

答案 0 :(得分:1)

类似以下内容将带您进入球场:

Sub test()
    'get that ugly b2 value into an array split by line
    Dim b2Array As Variant
    b2Array = Split(Sheet1.Range("B2"), Chr(10))

    'grab the value in a2
    Dim a2Value As String
    a2Value = Sheet1.Range("A2").Value

    'loop through the array (each line in B2 and output. Making use of more `split` here to grab values
    Dim writeRow As Integer: writeRow = 1
    For Each element In b2Array
        Sheet2.Cells(writeRow, 1).Value = a2Value
        Sheet2.Cells(writeRow, 2).Value = Trim(Split(Trim(element), " ")(0))
        Sheet2.Cells(writeRow, 3).Value = Trim(Replace(element, Split(Trim(element), " ")(0), ""))
        writeRow = writeRow + 1
    Next
End Sub

那是假定它在Sheet1上,并且您想输出到Sheet2。

答案 1 :(得分:0)

在Excel 2010或更高版本中,您可以使用Power Query(又名Get&Transform)执行此操作,然后在添加更多行时刷新查询。

  • 通过linefeed character将第2列拆分为
  • 修剪列2删除前导和尾随空格
  • space分成几列,但只有最左边的空格

这是M代码

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

    #"Split Column by Delimiter" = Table.ExpandListColumn(Table.TransformColumns
            (Source, {{"Column2", Splitter.SplitTextByDelimiter("#(lf)", QuoteStyle.Csv), 
            let itemType = (type nullable text) meta [Serialized.Text = true] in type {itemType}}}), "Column2"),

    #"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Column2", type text}}),

    #"Added Custom" = Table.AddColumn(#"Changed Type1", "Trim", each Text.Trim([Column2])),

    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Column2"}),

    #"Split Column by Delimiter1" = Table.SplitColumn(#"Removed Columns", 
            "Trim", Splitter.SplitTextByEachDelimiter({" "}, QuoteStyle.Csv, false), {"Trim.1", "Trim.2"})
in
    #"Split Column by Delimiter1"

原始数据

enter image description here

结果

enter image description here