首页 文章

excel / vba中的字符串解析,用数字和冒号分隔

提问于
浏览
0

我在VBA中设置了一个字符串,我从另一个程序中提取 . 当我将这些数据导入Excel时,它具有以下格式:

EXAMPLE EXAMPLE EXAMPLE EXAMPLE 
EXAMPLE EXAMPLE EXAMPLE EXAMPLE 

001: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE 

002: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE

003: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE

使用我当前的VBA代码,您单击一个表单控件,它将该数据放入单元格,就像我键入它一样 . 我想将它分开,所以当我点击控件时,它会将数据放入由数字分隔的单独单元格中 . 那是,

EXAMPLE EXAMPLE EXAMPLE EXAMPLE 
EXAMPLE EXAMPLE EXAMPLE EXAMPLE 

001: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE

进入第一个细胞,

002: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE

进入相邻的细胞,和

003: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE

进入下一个相邻的单元格,依此类推,无论我有多少数字 . 我希望我已经足够彻底地解释了我的情况以便有人帮忙 . 请原谅我对VBA很新的事实 .

3 回答

  • 0

    您可以使用Split并将数组处理到单元格中 . Selection对象上还有一个TextToColumns函数 .

  • 0

    这是我们使用的帖子multi delimiters split .

    你可能会从中得到一个想法 .

    • 检查行的开头是否以数字开头

    • 按空格,制表符或任何特定字符分割,而不是分隔符

    • 如果您有多个分隔符,则可以使用上述方法

    请评论您尝试过的内容 . 很高兴从那里得到帮助 .

  • 0

    使用regular expressons . 从 Tools -> References 添加对 Microsoft VBScript Regular Expressions 5.5 的引用 . 然后你可以编写如下代码:

    Public Function PasteValues()
    Dim s As String, re As New RegExp
    Dim matches As MatchCollection, m As Match
    
    Dim rng As Range
    'Destination workbook, worksheet within workbook, and starting cell
    Set rng = ActiveWorkbook.Worksheets(1).Range("A1")
    
    s = "EXAMPLE EXAMPLE EXAMPLE EXAMPLE " & Chr(13) & _
        "EXAMPLE EXAMPLE EXAMPLE EXAMPLE " & Chr(13) & _
        Chr(13) & _
        "001: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE " & Chr(13) & _
        Chr(13) & _
        "002: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE " & Chr(13) & _
        Chr(13) & _
        "003: EXAMPLE EXAMPLE EXAMPLE - EXAMPLE "
    
    'Finds a sequence of non-digits (\D) followed by either 
        '1) a sequence of digits followed by a colon -- (\d*:)
        '2) the end of the string -- $
    'The either/or is defined by the pipe -- |
    re.Pattern = "(\D*)((\d*:)|$)"
    
    'We want to match all instances, not just the first
    re.Global = True
    
    Set matches = re.Execute(s)
    For Each m In matches
        'Each item in the SubMatches collection corresponds to a pair of parentheses.
        'e.g. m.SubMatches(0) returns the matched string corresponding to (\D*)
        'In this case, we aren't interested (I'm assuming) in the actual numbers, just that
        'they are there, but we could see them using SubMatches(1) or SubMatches(2)
        rng.Value = m.SubMatches(0)
    
        'Advance the range to the next column
        Set rng = rng.Offset(, 1)
    Next
    End Function
    

相关问题