プロが教えるわが家の防犯対策術!

下記のような記述だと1つ目の「天気」の文字列は取得できても
2つ目の「晴れ」の文字列を取得することができません。
どうすれば2つ目の文字列を取得することができるのでしょうか?
※「<」と「>」で挟まれている間の文字列を取得したいです。
※「<」と「>」が何組あるかは不明です。

Dim str0, str1, str2 As Variant
Dim 指定1, 指定2 As Variant

str0 = ”今日の<天気>は<晴れ>です。
指定1 = ”<”
指定2 = ”>”
str1 = Mid(str0, Len(指定1) + InStr(1, str0, 指定1)
str2 = Left(str1, InStr(1, str1, 指定2) - 1)


使用OS:Windows 8
使用ソフト:Microsoft Excel 2007

ご存知の方がおられましたらご回答をよろしくお願いいたします。

A 回答 (2件)

> ※「<」と「>」が何組あるかは不明です。



っていうなら、str1、str2・・・・ じゃダメですよね。
際限なく str3・・・・str100 とか宣言するわけにもいかないし。

Dim str0 As Variant
Dim str1() As Variant
Dim stIdx As Integer
Dim 指定1 As Variant
Dim 指定2 As Variant
Dim ptA As Integer
Dim ptZ As Integer

指定1 = "<"
指定2 = ">"

str0 = "今日の<天気>は<晴れ>です。<雨>や<曇り>だったり<大荒れの嵐>もあるかも。"

ReDim str1(Int(Len(str0) / 2)) As Variant

ptZ = 1
stIdx = 0

Do Until InStr(ptZ, str0, 指定1) = 0
stIdx = stIdx + 1
ptA = InStr(ptZ, str0, 指定1)
ptZ = InStr(ptZ + 1, str0, 指定2)
str1(stIdx) = Mid(str0, ptA + 1, ptZ - ptA - 1)
MsgBox (str1(stIdx))
Loop

解読はご自身でトライしてみてください。
    • good
    • 1
この回答へのお礼

ご回答いただき、ありがとうございました。
とっても分かりやすかった為、すぐに解決する事ができました!

お礼日時:2017/09/20 15:20

こういうときは 私なら、InStr関数を使うかな。


あんまりスマートなコード例じゃないかもしれないけど、解読してみて下さい。


Dim str0, str1, str2 As Variant
Dim 指定1, 指定2 As Variant
Dim ptA As Integer
Dim ptZ As Integer

str0 = "今日の<天気>は<晴れ>です。"
指定1 = "<"
指定2 = ">"

ptA = InStr(1, str0, 指定1)
ptZ = InStr(1, str0, 指定2)

str1 = Mid(str0, ptA + 1, ptZ - ptA - 1)

ptA = InStr(ptZ, str0, 指定1)
ptZ = InStr(ptZ + 1, str0, 指定2)

str2 = Mid(str0, ptA + 1, ptZ - ptA - 1)

MsgBox (str1)
MsgBox (str2)
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!