• ベストアンサー

ExcelでRegExpのFunctionの作成

エクセルVBAで、文字列と正規パターンを引数として渡すと、マッチした文字位置の羅列を","区切りの文字列で返すようなFunctionを作ろうと考えています。なかなかうまく作れなくて困っています。どなたか、詳しいかたいらっしゃいましたら教えて頂けないでしょうか?宜しくお願いいたします。 発生する実行時エラー 実行時エラー'5020': 'Execute'メソッドは失敗しました:'IRegExp2'オブジェクト 追伸:ネットで、自動作成してくれるサイトがありそのコードを参考にアレンジしました。つじつまが合わない部分は、私の改編によるものだと思います。 Function Get_Position_RegExp(MySource As String, MyPattern As String) As Variant Dim MyReg As RegExp Dim MyMatch As MatchCollection Dim i As Match Set MyReg = CreateObject("VBScript.RegExp") With MyReg .Pattern = MyPattern .Global = True Set MyMatch = .Execute(MySource) End With Get_Position_RegExp = "" For Each i In MyMatch Get_Position_RegExp = Get_Position_RegExp & "," & i.FirstIndex + 1 Next Set MyMatch = Nothing Set MyReg = Nothing End Function

質問者が選んだベストアンサー

  • ベストアンサー
  • KenKen_SP
  • ベストアンサー率62% (785/1258)
回答No.2

Function プロシージャに致命的なエラーはありません。#1 ご回答のように マッチパターン(MyPattern)の指定に誤りがあるようですね。 細かな部分を若干修正してみました。ご参考までに。 Sub TestProc()   Dim s As String   s = Get_Position_RegExp("RegExpテスト。RegExpでマッチ位置を調べる。", _               "RegExp")   MsgBox s End Sub ' // MyPattern にマッチする位置をカンマ区切りの文字列で返す Function Get_Position_RegExp( _   ByVal MySource As String, _   ByVal MyPattern As String _ ) As String   Dim MyReg  As RegExp   Dim MyMatch As MatchCollection   Dim i    As Match   Dim s    As String   Set MyReg = CreateObject("VBScript.RegExp")   With MyReg     .Pattern = MyPattern     .IgnoreCase = False   ' 大文字・小文字を区別しない     .Global = True     Set MyMatch = .Execute(MySource)   End With   If MyMatch.Count > 0 Then     For Each i In MyMatch       ' // カンマは後ろにつける       s = s & CStr(i.FirstIndex + 1) & ","     Next     ' // 末尾の余計なカンマを落とす     Get_Position_RegExp = Left$(s, Len(s) - 1)   End If   Set MyMatch = Nothing   Set MyReg = Nothing End Function

vba_minarai
質問者

お礼

丁寧な回答ありがとうございます。 パターンを調べたところ、ご指摘の通り間違いがありました。 その上、至らない部分を修正までして頂き大変助かります。 何が、至らなかったのか?なぜ、カンマは後につけるのか?などその意味についてじっくりと考えていきたいと思います。本当にありがとうございました。

その他の回答 (1)

  • Wendy02
  • ベストアンサー率57% (3570/6232)
回答No.1

こんにちは。 >実行時エラー'5020': >'Execute'メソッドは失敗しました:'IRegExp2'オブジェクト それは、パターンの書き方を間違えているのですね。

vba_minarai
質問者

お礼

ご指摘の通り、パターンを間違えていました。 Instr関数だけでは、効率よくヒットできないので、正規表現の併設としました。ありがとうございました。

関連するQ&A

  • Excel : 正規表現を利用して2文字の全角数字を半角数字に変換するには?

    アクティブセルの文字を、正規表現を利用して文字の変換をしたいと考えています。 2文字の全角数字を半角数字に変換します。 かつ、3文字以上の全角数字は変換しません。 下記のようにコードを書いたのですが、希望通りに動作してくれません。 どこが悪いのでしょうか? ご指摘いただければ幸いです。 よろしくお願いいたします。 ※参照可能なライブラリファイルにて、「Microosft VBScript Regular Expressions 5.5」に  チェックは入れています。 Sub sample()   Dim str   Dim strPattern As String   Dim strReplacement As String      str = ActiveCell.Value   str = myRegExp(str, "([^0123456789])([0123456789]{2})([^0123456789])", "$1$2$3")   ActiveCell.Value = str End Sub Private Function myRegExp(str, strPattern, strReplacement)   Dim objRegExp As RegExp   Dim test As String   Set objRegExp = New RegExp   With objRegExp     .Pattern = strPattern     .IgnoreCase = False     .Global = True     myRegExp = .Replace(str, "$1" & StrConv("$2", vbNarrow) & "$3")   End With   Set objRegExp = Nothing End Function

  • Functionでの戻り値のとり方

    こんばんわ。 以下のように、Functionで引数に配列を指定して、戻り値も配列で取得したいのですが、方法としては以下のようにしかできないのでしょうか? ------------------------- '配列を宣言 dim Ary() as string dim AryRet() as string '戻り値の配列 Call Get_Ary(Ary(),AryRet()) ------------------------- Function Get_Ary(Ary() as string , AryRet() as string) 'Ary()を参照して、AryRet()を取得する End Function という風に書いているのですが、Functionのところを以下のように 書くのは無理でしょうか? うまく取れないというのはやっぱ無理なのかな・・ ------------------------- '配列を宣言 dim Ary() as string dim AryRet() as string '戻り値の配列 AryRet() = Get_Ary(Ary()) Function Get_Ary(Ary() as string) As string 'Ary()を参照して、AryRet()を取得する 'それを関数の戻り値とする Get_Ary = AryRet(index) End Function このように書くと、配列の最後のインデックスの値だけ取れてしまう ようなんですが、、やっぱ配列で返すというのは上記のやり方でないと 無理なのでしょうか? 詳しい方ご教示願います。

  • 作成方法についての質問です。

    下記のマクロで実行すると添付画像[現状]のようになってしまいます。 私としては[こうなってほしい]の形にしたいのですが、どこに何を組み込めばよいかわかりません。 誰か教えてください。 Dim Matches As Object Dim Match As Object Dim i As Long, j As Long Dim a As Variant With CreateObject("VBScript.RegExp") Set rng = Range("A1", Cells(Rows.Count, 1).End(xlUp)) Application.ScreenUpdating = False For i = 1 To rng.Rows.Count If InStr(1, rng.Cells(i, 1).Value, "(", 1) > 0 Then .Pattern = "\(([A-z\d,]+)" Else .Pattern = "([A-z\d,]+)" End If .Global = True Set Matches = .Execute(StrConv(rng.Cells(i, 1).Value, vbNarrow)) If Matches.Count > 0 Then a = Matches(0).SubMatches(0) a = Split(a, ",") Cells(i, 2).Resize(, UBound(a) + 1).Value = a End If j = 0 Next End With Application.ScreenUpdating = True Set rng = Nothing End Sub

  • EXCELで作ったマクロを別のファイルのEXCELでも使えるようにしたいです。

    (1)EXCELファイルでマクロを作成しました。 (実際はここである人の知恵をお借りして作ったものですが…) しかし、(2)EXCELファイルで(1)EXCEL作成マクロが実行できません。 どのような処理をすれば、どのPCでも、どのファイルでも実行できるようなマクロに出来るのでしょうか?? 以下にそのマクロを示します。 ↓↓↓ Sub 文字置換() '半角カタカナを全角に、全角英数を半角にするマクロ (Excel編) Dim rng As Range Dim Re As Object Dim myPat As String Dim c As Range Dim Matches As Object Dim Match As Object Dim Str1 As String Dim Str2 As String Dim buf As String Dim t As Long On Error Resume Next Set rng = ActiveSheet.UsedRange.SpecialCells _ (xlCellTypeConstants, xlTextValues) On Error GoTo 0 If rng Is Nothing Then MsgBox "変換する対象が見当たりません。", 48 Exit Sub End If '全角側 --- 半角側 (!-/ を加えれば記号も半角) myPat = "([\uFF66-\uFF9F]*)([!-}]*)" '正規表現のパターン Set Re = CreateObject("VBScript.RegExp") Application.ScreenUpdating = False With Re .Global = True .IgnoreCase = True .Pattern = myPat For Each c In rng.Cells Set Matches = .Execute(c.Value) If Matches.Count > 0 Then buf = c.Value For Each Match In Matches If Len(Match.Value) > 0 Then Str1 = StrConv(Match.SubMatches(0), vbWide) If Str1 <> "" Then '0 =vbBinaryCompare buf = Replace(buf, Match.SubMatches(0), Str1, , , 0) End If Str2 = StrConv(Match.SubMatches(1), vbNarrow) If Str2 <> "" Then buf = Replace(buf, Match.SubMatches(1), Str2, , , 0) End If End If Str1 = "": Str2 = "" Next Match If buf <> c.Value Then c.Value = buf t = t + 1 End If End If Next c End With Set Re = Nothing Application.ScreenUpdating = True If t > 0 Then MsgBox t & "個のセルを変換しました。", 64 End If End Sub 出来れば、置換した文字数をメッセージBOXに表示したいです。

  • VBSのRegExpの拡張機能を有効にするには

    VBScriptのRegExpオブジェクトで拡張機能を有効にするにはどのようにすればいいのでしょうか。例えば、後方一致(先読み)は正しく実行できますが、前方一致(後読み)は拡張機能となっているためそのままではエラーになりますがどのようにすれば前方一致(後読み)の機能が使えるようになるのでしょうか。(OSはWindowsXPです) ------------------------------------- Option Explicit dim a dim bs dim b Dim o Set o = new RegExp o.IgnoreCase = False o.Global = True o.pattern = "\d+(?=年)"            '後方一致  <OK> 'o.pattern = "(?<=昭和)\d+"         '前方一致  <ERROR> a="昭和45年と平成26年" Set bs = o.Execute(a) For Each b in bs  WScript.echo b.FirstIndex+1 & "文字目の" & b.Value & "がマッチしました" Next Set o = Nothing -------------------------------------

  • 【VBA】【正規表現】

    23歳OLです。 VBAと正規表現についての質問です。 ▼やりたいこと ================================================ 1 | 0 |1234567890 | 2014-2-22 22:22:22.06+09 という数列から 1234567890 という数字のみを抜き出したいです。 正確には2本目の|と3本目の|の間に入っている様々な数字です。 ※桁数が固定されていません。 ================================================ ▼実際書いたコード ================================================ Sub Sample2() Dim RE, strPattern As String, i As Long, msg As String, reMatch Set RE = CreateObject("VBScript.RegExp") strPattern = "☆この部分☆" With RE .Pattern = strPattern .IgnoreCase = True .Global = True For i = 1 To 10 Set reMatch = .Execute(Cells(i, 1)) If reMatch.Count > 0 Then msg = msg & reMatch(0).Value & vbCrLf End If Next i End With MsgBox msg Set reMatch = Nothing Set RE = Nothing End Sub ================================================ ☆この部分に☆に何を入れればよいでしょう? ご指導よろしくおねがいします。

  • 正規表現について

    VB6ですが・・・ '次のようなコードがあって <!-- と --> に囲まれる文字列を抜き出したのですが 'どのようなパターンマッチを書けばいいのでしょうか? 'HTMLのコメントのみを抜き出したいと思っています。 Const s = "<!--今日-->" _ & "<!--僕は--><!--正規表現を--><!--勉強します-->" Dim x As RegExp Dim v As match Set x = New RegExp x.Pattern = "パターン" x.Global = True For Each v In x.Execute(s) Debug.Print v.Value Next

  • 【VBA】半角カタカナのみを全角にするには?

    http://bekkoame.okwave.jp/qa8979427.html こちらのページを参考にしたのですが カタカナのみ全角にしたいのですが 平仮名がカタカナになってしまいます。 正規表現と言うのがよくわからないので コピペで使ってますが Sub Sample2() Dim myStr As String Dim Match As Object, Matches As Object Dim CW As String With CreateObject("VBScript.RegExp") .Pattern = "[\uFF61-\uFF9F]+" '---(1) .Global = True myStr = "あああイイイ" If Len(myStr) > 0 Then Set Matches = .Execute(myStr) 'マッチしたすべての文字列を置換 For Each Match In Matches myStr = Replace(myStr, Match.Value, _ StrConv(Match.Value, vbWide)) '---(2) Next Match CW = myStr End If End With End Sub だと「あああ」は平仮名のままなのですが myStr = "のののノノノ" にすると、ひらがなの「ののの」が全角カタカナになってしまいます。 Sub test() Call KanaJisF("あああイイイ") End Sub Function KanaJisF(ByVal sSrc As String) As String Dim sTempW As String Dim sTempN As String Dim i As Long ' ' 全角カナに相当する文字コードを総当たりでループ For i = -31852 To -31936 Step -1 sTempW = Chr(i) ' 全角カナ変数に格納 sTempN = StrConv(sTempW, vbNarrow) ' 半角カナに変換して変数に格納 ' ' 半角カナ各文字が、文字列に含まれている場合、全角カナに置換 If InStr(1, sSrc, sTempN) Then sSrc = Replace(sSrc, sTempN, sTempW) Next i ' ' 半角長音、文字列に含まれている場合、全角長音に置換 sTempN = Chr(176) If InStr(sSrc, sTempN) Then sSrc = Replace(sSrc, sTempN, "ー") KanaJisF = sSrc End Function こちらのコードは、「あああ」も全角カタカナになりました。 "のののノノノ"も同様です。 平仮名は平仮名のままにしたいのですが そのような方法はありますか?

  • ExcelのVBAの正規表現で二重引用符を含む文字列を検索できるようにしたい

    二重引用符を含む文字列を検索できるようにするには 下記の記述の re.Pattern = "<hr class=\"separate\">" の部分をどのように直せばよいのでしょうか? Sub tagCount() Dim cnt As Integer Dim IE As Object Dim HTML As String Set IE = CreateObject("InternetExplorer.Application") IE.Navigate ("http://www.yahoo.co.jp/") While IE.busy: Wend While IE.Document.readyState <> "complete": Wend HTML = IE.Document.body.innerHTML IE.Quit Dim re As RegExp Dim mc As MatchCollection Dim m As Match Set re = New RegExp re.Pattern = "<hr class=\"separate\">" re.Global = True re.IgnoreCase = True Set mc = re.Execute(HTML) MsgBox mc.Count End Sub ご存知の方がおられましたらご回答をよろしくお願いします。 使用OS:Windows XP 使用ソフト:Microsoft Excel 2003

  • UTF8で作成されたHTMLファイルの表示について

    WebBrowserをフォームに貼り付け、次のようなコードを記載してたのですが、表示が文字化けしてしまいます。どうすればよいでしょうか? Private Sub Form_Load() Dim html As String Dim pDoc As Object html = ReadFileData("UTF8.html") Set pDoc = New MSHTMLCtl.HTMLDocument WebBrowser1.Navigate "about:blank" Set pDoc = WebBrowser1.Document pDoc.writeln html Set pDoc = Nothing End Sub Public Function ReadFileData(ByVal FileName As String) As String Dim bytArray() As Byte Dim intFileNo As Integer Dim lngFileLenB As Long lngFileLenB = FileLen(FileName) ReDim bytArray(lngFileLenB - 1) intFileNo = FreeFile Open FileName For Binary As #intFileNo Get #intFileNo, , bytArray Close #intFileNo ReadFileData = StrConv(bytArray, vbUnicode) End Function 環境:VB6+WinXP

専門家に質問してみよう