2016-08-10 35 views
3

私はこのようなセルの値を持っている:Excel VBA:セルから部分文字列を削除するにはどうすればよいですか?

This is a <"string">string, It should be <"changed">changed to <"a"> a number. 

この部分<" ">で繰り返すいくつかの単語があります。私は、セルの値を変更するために、Excel VBAを使いたい

This is a string, It should be changed to a number. 

すべてのヘルプは理解されるであろう。ありがとう。

+0

を試してみてください、私は(HTTP [正規表現(正規表現)]を使用することをお勧めします:/ /stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops)不要な部分文字列を削除します。 – Ralph

+0

<" ">は実際にそこにいますか?それとも、同じ言葉を二度続けて行かないようにしようとしているのですか? –

答えて

2

で終わる、この場合には、このコード

Sub DelDoubleString() 
Dim Text As String, Text2Replace As String, NewText As String 
On Error Resume Next  'Optional, in case there's no double string to be deleted 
Text = Cells(1, 1) 

Do 
    Text2Replace = Mid$(Text, InStr(Text, "<"), InStr(Text, ">") - InStr(Text, "<") + 1) 
    NewText = Application.WorksheetFunction.Substitute(Text, Text2Replace, vbNullString) 
    Text = NewText 
Loop Until InStr(NewText, "<") = 0 

Cells(1, 1) = NewText 

End Sub 
1

あなたのテキストを含むセルを選択し、この短いマクロを実行します。

Sub Kleanup() 
    Dim d As Range, s As String, rng As Range 
    Dim gather As Boolean, L As Long, DQ As String 
    Dim i As Long, s2 As String, CH As String 

    Set rng = Selection 
    DQ = Chr(34) 

    For Each r In rng 
     s = Replace(r.Text, "<" & DQ, Chr(1)) 
     s = Replace(s, DQ & ">", Chr(2)) 
     gather = True 
     L = Len(s) 
     s2 = "" 
     For i = 1 To L 
      CH = Mid(s, i, 1) 
      If CH = Chr(1) Then gather = False 
      If CH = Chr(2) Then gather = True 
      If gather And CH <> Chr(2) Then s2 = s2 & CH 
     Next i 
     r.Value = s2 
    Next r 
End Sub 
-1

Uは正規表現を使用するように提案フォローアップ機能

ActiveSheet.Cells(1, 1).Value = Replace(ActiveSheet.Cells(1, 1).Value, "String", "Number") 
+0

彼女は何の質問もしていません。 –

3

を交換して使用することができ、ここでの例です:

Option Explicit 

Sub RemoveByRegexWithLateBinding() 

    Dim strIn As String 
    Dim strOut As String 
    Dim objRegex As Object 

    'input 
    strIn = "This is a <""string"">string, It should be <""changed"">changed to <""a""> a number." 
    Debug.Print "Input:" & vbCr & strIn 

    'create and apply regex 
    Set objRegex = CreateObject("VBScript.RegExp") 
    objRegex.Pattern = "<""[^<>""]*"">" 
    objRegex.Global = True 
    strOut = objRegex.Replace(strIn, "") 

    'test output 
    Debug.Print "Output:" & vbCr & strOut 

End Sub 

この出力を生成します。

正規表現の
Input: 
This is a <"string">string, It should be <"changed">changed to <"a"> a number. 
Output: 
This is a string, It should be changed to a number. 

図:

enter image description here

という文字列を見つけることのように説明することができる。

  • <"
  • で始まるが、文字<から離れて何が含まれています>および"
  • がセルA1にテキストを想定し">
+1

'objRegex.Pattern'の仕組みが分かりません。使用するには複雑すぎるようです... –

+0

@PatrickLepelletier - regexesは急な学習曲線ですが、努力する価値があります。私の答えの正規表現は、基本的に '<' '>'と '' 'を除いて' <"' and '"> 'のものとマッチすると言います。パターンの中の' '' 'が必要であるため、 VBAは文字列に '' 'を使用し、パターンには値に' ''が必要です。実際にはこのパターンは '<"[^<>"] * ">'です。 –

関連する問題