2016-08-22 2 views
1

아래 코드는 셀에 문자열을 찾고 그 앞에 오는 단어와 단어를 모두 추출합니다.셀 배열의 문자열 추출

검색 단어가 "(안녕하세요)"로 남겨지면 코드가 작동하지만 "안녕하세요"로 만들면 코드에서 찾을 수 없습니다. "hello"와 "hey"사이의 공백을 가정하지만 그 변경 방법을 잘 모릅니다.

Dim c As Range, v As String, arr, x As Long, e 
    Dim d As Range 


    Set d = WorkSheets("Sheet1").Range("F1") '<<results start here 

    For Each c In ActiveSheet.Range("D1:D10") 
     v = Trim(c.Value) 
     If Len(v) > 0 Then 

      'normalize other separators to spaces 
      v = Replace(v, vbLf, " ") 
      'remove double spaces 
      Do While InStr(v, " ") > 0 
       v = Replace(v, " ", " ") 
      Loop 

      'split to array 
      arr = Split(v, " ") 
      For x = LBound(arr) To UBound(arr) 
       e = arr(x) 
       'see if array element is a word of interest 
       If Not IsError(Application.Match(LCase(e), Array("(hello hey)"), 0)) Then 
        If x > LBound(arr) Then 
         d.Value = arr(x - 1) & " " & e 'prepend previous word 
        Else 
         d.Value = "??? " & e 'no previous word 
        End If 
        Set d = d.Offset(1, 0) 
       End If 
      Next x 
     End If 
    Next c 
End Sub​ 

enter image description here

+2

"(안녕하세요 헤이)"는 공백을 포함하므로 절대 일치하지 않으며 모든 셀 값을 공백으로 나눕니다 (따라서'arr'의 값에는 공백이 포함되지 않습니다). –

+0

@TimWilliams 괄호 내부를 단일 vaule로 처리 할 수있는 방법이 있습니까? – johndoe253

답변

1

, 당신은 공간에 의해 다음 검색 단어로 분할 할 수 있습니다

Dim ws1 as WorkSheet, d As Range, c As Range 
Dim v As String, arr() As String 

Set ws1 = WorkSheets("Sheet1") 
Set d = ws1.Range("F1") '<<results start here 

For Each c In ws1.Range("D1:D10") 
    v = WorksheetFunction.Trim(c.Value2) ' the Excel function TRIM() also replaces extra spaces between words to one space 
    arr = Split(v, "(hello hey)") 
    If UBound(arr) > 0 Then 
     v = arr(0) 
     v = Replace(v, vbLf, " ") 
     v = Trim(v) 
     arr = Split(v) ' split by space to get the last word before the search word 
     v = arr(UBound(arr)) ' the last word in arr 

     d.Value2 = v 
     Set d = d.Offset(1) 
    End If 
Next c 
+0

도움 주셔서 감사합니다! – johndoe253

1

한 가지 방법은 다른 문자와 최초의 우주를 대체 (예를 들어, ^)를 그대로 공간의 나머지 부분을 떠날 것입니다. 이제 새롭게 도입 된 char을 기반으로 문자열을 분할합니다.

그래서, Hi (hello hey) ---> Hi^(hello hey) ---> arr(0)= Hi and arr(1)= (hey hello)

편집 :는 여러 항목을 처리하는 코드를 업데이트했습니다. 공간을 교체하는 대신 ()을 대체하십시오. 자세한 내용은 코드 내부의 주석을 참조하십시오. 대신 공간에 의한 분리의

Sub test() 

    Dim c As Range, v As String, arr, x As Long, e 
    Dim d As Range 

    Dim arr2 


    Set d = Worksheets("Sheet1").Range("F1") '<<results start here 

    For Each c In ActiveSheet.Range("D1:D10") 
     v = Trim(c.Value) 
     If Len(v) > 0 Then 

      'normalize other separators to spaces 
      v = Replace(v, vbLf, " ") 
      'remove double spaces 
      Do While InStr(v, " ") > 0 
       v = Replace(v, " ", " ") 
      Loop 

      '/ Replace just the first space with^
      'v = Replace(v, Space(1), "^", , 1) --- Commented as it wont work with multiple entries 

      '/ Updated as per your edit in question. 
      '/ Replace parenthesis with^appended. 
      v = Replace(v, Space(1) & "(", "^(") 
      v = Replace(v, ")", ")^") 

      'split to array 
      '/ Now split the array on ^, this way you get to keep the full string inside parenthesis 
      arr = Split(v, "^") 

      For x = LBound(arr) To UBound(arr) 
       e = arr(x) 
       'see if array element is a word of interest 
       If Not IsError(Application.Match(LCase(e), Array("(hello hey)"), 0)) Then 
        If x > LBound(arr) Then 
         d.Value = arr(x - 1) & " " & e 'prepend previous word 

         '/ This part added as per your edit. 
         '/ It will bring back the word which precedes the search term. 
         arr2 = Split(StrReverse(Trim(arr(x - 1))), Space(1)) 
         If UBound(arr2) > 0 Then 
          arr2(UBound(arr2)) = "" 
         End If 
         d.Value = Trim(StrReverse(Join(arr2, Space(1)))) & " " & e 

        Else 
         d.Value = "??? " & e 'no previous word 
        End If 
        Set d = d.Offset(1, 0) 
       End If 
      Next x 
     End If 
    Next c 

End Sub 
+0

셀에있는 문장이있을 때 그것은 얻을 수 없지만 단지 HI (안녕하세요) 일 때. 셀의 들여 쓰기와 문장을 어떻게 설명 할 수 있습니까? – johndoe253

+0

스크린 샷을 추가하겠습니다. – johndoe253

+0

스크린 샷에서 거의 모든 HI를 가져 왔지만 마지막 단 하나는 단락에 있습니다. – johndoe253

1

을 그때 정규식 전에 마지막 단어를 찾기 위해 텍스트 문구를 찾기 위해 측량기를 사용 문구.

Function getWordBeforePhrase(text As String, phrase As String) As String 

    Dim regex As Object, Match As Object 
    Dim lEnd As Long 

    lEnd = InStr(text, phrase) - 1 

    If lEnd Then 
     text = Left(text, lEnd) 

     Set regex = CreateObject("VBScript.RegExp") 
     With regex 
      .Global = True 
      .Pattern = "\w+" 
      Set matches = regex.Execute(text) 

     End With 

     If matches.Count Then getWordBeforePhrase = matches(matches.Count - 1).Value 

     Set regex = Nothing 

    End If 

End Function 
+0

'InStr'이 필요 없습니다. 그냥 하나의 정규식을 사용하십시오. '\ w + (? = \ W * "& phrase &") "'와 같은 것입니다. 'phrase '를 입력 할 때 괄호를 벗어나면 조심해야합니다. 예 : ''\ (hello hey \)''또는 다른 특수 문자. –

+0

감사합니다. 비슷한 것을 시도했지만 제대로 작동하지 못했습니다. –

+0

도움 주셔서 감사합니다. – johndoe253