【问题标题】:How to parse part of a cell containing x.x.x. and copy the data to another cell?如何解析包含 x.x.x 的单元格的一部分。并将数据复制到另一个单元格?
【发布时间】:2017-04-17 18:03:29
【问题描述】:

我有一个 excel 文件我想解析 D 列中每个单元格的开头,然后复制并粘贴单元格中的数字(同一行,B 列) 如何解析数字为 0 到 9 和“。”的单元格并将该值 x.x.x.x 复制到 B 列?在 D 列的单元格开头没有多少数字和句点的标准格式。它可以是 1.3.4 或 1.3.4。或 1.3 等...

===================================================================== 
'DIMENSIONING VARS AND PATHS
Dim Level As Range
Dim i, j, q(1 To 50) As Long
Dim numofchar As Long
Dim filepath As String
Dim filename As String
Dim PN As String
Dim HEADERrowcallout As Long
Dim LASTREQrowcallout As Long
Dim REQTEXTcolumncallout As String
Dim x As Long
Dim s As String
Dim count As Long
Dim Reqtext As Variant
Dim SectionText As Variant
'

'scanf(Input the correct row and column numbers). Used for determining start and endpoints of filtering files
HEADERrowcallout = InputBox("What row number are your headers in?")
LASTREQrowcallout = InputBox("What row number are your headers in?")
REQTEXTcolumncallout = InputBox("What is the column letter where ReqText is located? (A=1,B=2,D=4,ect...)")
'REQTYPEcolumncallout = InputBox("What is the column number from the left where the outline level is located? (A=1, B=2, ect...)")
'SECTIONcolumncallout = InputBox("What is the column number from the left where the outline level is located? (A=1, B=2, ect...)")
'


'stop screen updating
Application.ScreenUpdating = False
'

'show gridlines
ActiveWindow.DisplayGridlines = True
'

'Requirement Text to Section Maker --- Part (1)
'Part 1 filter string for the section number. (Numbers 1-10 & . until letters or space)
'Generate a string using the numbers and letters, ex [1.1.3.], cut & copy data to section column same row
For i = HEADERrowcallout + 1 To LASTREQrowcallout

    'Get length of active cell. This is max that copied cell will be

    LengthCell = Len(Cells(HEADERrowcallout + 1, REQTEXTcolumncallout))
    SectionText = (LengthActiveCell)
    Reqtext = (LengthActiveCell)

        'while count != length, scan each array position from 0 until array position value != 1-10 or .
        While x < LengthActiveCell
            Select Case Cells()
            Case "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."
            Dim count As Long
            x = x + 1

        'If no more letters or .s, move to next cell
            x = LengthCell
    'if SectionText() = SectionText(0)

    'Keep going down ReqText column until specified end
    HEADERrowcallout = HEADERrowcallout + 1


End Sub
===========================

Picture of Excel Sheet

【问题讨论】:

  • 换句话说,您只是想从 D 列的单元格中提取数字?这会起作用吗? =MID(D1,1,SEARCH(" ",D1)-1)?
  • 为什么选择 VBA?你只能使用公式来做到这一点。
  • 我不知道如何在公式中做到这一点。此外,“ ”并不总是出现在句点或数字之后。

标签: excel vba parsing text


【解决方案1】:

编辑:现在用 cmets 解释代码的作用

显然,您的实时版本中不需要 cmets。

将下面的代码粘贴到一个新的Module中,然后将其用作WorksheetFunction (我猜测应该调用什么函数)。在任何单元格中,输入=ExtractOutline(&lt;cell address&gt;),其中&lt;cell address&gt; 是您希望从中提取x.x.x 的单元格。少量。

Function ExtractOutline(strInput As String)

    'Function iterates through the input string until we get to a
    'character which isn't one in "0123456789." Each character which is
    'one of these is added to the output as we go along

    Dim strOut As String        'The output we're building
    Dim intPos As Integer       'The position we've reached in the input
    Dim str1Char As String      'The character found at the current position

    intPos = 1     'We'll start at the first character
    str1Char = Mid(strInput, intPos, 1)       'Extract the intPos-th character, in this case, the 1st.

    While intPos <= Len(strInput) And WorksheetFunction.Find(str1Char, "0123456789." & str1Char) < 12

    'While
    'intPos <= Len(strInput) 
    'This makes sure we haven't iterated beyond the end of the input

    'AND
    'WorksheetFunction.Find(str1Char, "0123456789." & str1Char) < 12
    'Looks for the current character in "0123456789."
    'If it wasn't found we'd get an error (as output to the function)
    'To prevent that add current character to end of "0123456789."
    'Since "Find" returns the position, within the string,
    'and "01234567890." as 11 characters, we only match the right bit if it
    'is found before the 12th character

    'Add the character to the output
    strOut = strOut & Mid(strInput, intPos, 1)

    'Increment ready for next time round the loop
    intPos = intPos + 1
    'Get the next character to be checked
    str1Char = Mid(strInput, intPos, 1) 

    Wend

    ExtractOutline = strOut

End Function

【讨论】:

  • 我理解这段代码,但是如何将单元格文本值作为字符串传递给函数?
  • 如果您将代码放入新模块中,您可以在任何单元格中输入=ExtractOutline(A1),并且如果单元格 A1 是您的 x.x 之一。输入字符串,它将只返回相关部分。
  • 在代码中,您最初采用第一个字符,然后从第一个字符 (str1Char) 作为参数,第二部分是“”0123456789。”& str1Char
  • find 函数返回到字符串中出现表达式的位置,如果找不到则返回错误。我必须避免该错误,以确保找到它我附加了str1Char&lt;12 是因为如果它不在前 11 个字符中,我不想继续。可能有更好的方法,但这是我首先想到的。
  • 如果我之前的评论没有帮助,我在编辑我的答案时对其进行了扩展......在代码中添加了很多额外的 cmets。如果您使用它并觉得它满意,请将我的回答标记为已接受,以表示感谢(并帮助其他正在寻找类似问题答案的用户)。
【解决方案2】:

或者您可以将以下方法合并到您的代码中...

Sub Alex()
Dim lr As Long
Dim rng As Range, cell As Range
Dim RE As Object
Dim Match As Object

lr = Cells(Rows.Count, 4).End(xlUp).Row
Set rng = Range("D2:D" & lr)
Set RE = CreateObject("VBScript.RegExp")

RE.Pattern = "([0-9]\.){1,}"

For Each cell In rng
If RE.test(cell.Value) = True Then
   Set Match = RE.Execute(cell.Value)
   cell.Offset(0, -2).Value = Left(Match(0), Len(Match(0)) - 1)
End If
Next cell
End Sub

【讨论】:

  • 非常接近,但这在我的测试中还不够贪心。
  • 对于1.3.4,它抓取1.3,对于1.3,它抓取1
  • 但根据示例数据,它应该是 1.3.4。 X.... 或 1.3。 X.... 然后它分别返回 1.3.4 和 1.3。
【解决方案3】:

像这样的

您可以查看 RegExp 示例 here

代码

Sub EddieBetts()

Dim rng1 As Range
Dim lngCnt As Long
Dim objRegex As Object
Dim X

Set rng1 = Range([d2], Cells(Rows.Count, "D").End(xlUp))
X = rng1.Value2
Set objRegex = CreateObject("VBScript.RegExp")
objRegex.Pattern = "([0-9\.])+"

For lngCnt = 1 To UBound(X, 1)
    If objRegex.test(X(lngCnt, 1)) Then X(lngCnt, 1) = objRegex.Execute(X(lngCnt, 1))(0)
Next

rng1.Offset(0, -2).Value2 = X

End Sub

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-03
    • 1970-01-01
    相关资源
    最近更新 更多