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 很陌生。

4

3 回答 3

0

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

于 2012-12-19T15:13:47.313 回答
0

使用正则表达式。添加对Microsoft VBScript Regular Expressions 5.5from的引用Tools -> References。然后你可以编写如下代码:

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
于 2012-12-20T09:07:26.270 回答
0

这是我们使用多分隔符 split的帖子。

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

  • 检查行首是否以数字开头
  • 按空格、制表符或任何特定字符分割,而不是作为分隔符
  • 如果您有多个分隔符,您可以使用上述方法

请评论您尝试过的内容。很高兴从那里提供帮助。

于 2012-12-20T07:44:00.823 回答