正規表現を用いたユーザ定義関数を2つ書きました。MyFunc1は文字列から半角英数字だけを取り出す関数で、MyFunc2は半角英数字以外がある時に「Error(文字列)」を返す関数です
質問のデータがどのように引き渡されるのか分かりませんので、とりあえずエクセルのユーザ定義関数として作りました。ワークシートに値を入力して関数の動作を確認してみてください。仕様に問題がなければロジックだけを流用できると思います。関数は
=MyFunc(A1)
のようにして使います(A1はデータの入力されたセルアドレス)
Function MyFunc1(ByVal trg As Range) As String
'半角英数字を取り出す
Dim RE, mchItems
Dim strPattern As String
Dim idx As Integer
If trg <> "" Then
Set RE = CreateObject("VBScript.RegExp")
strPattern = "[0-9A-Z]"
With RE
.Pattern = strPattern
.IgnoreCase = True
.Global = True
Set mchItems = .Execute(StrConv(trg.Value, vbNarrow))
If mchItems.Count > 0 Then
For idx = 0 To mchItems.Count - 1
MyFunc1 = MyFunc1 & mchItems(idx).Value
Next idx
End If
End With
Set RE = Nothing
End If
End Function
Function MyFunc2(ByVal trg As Range) As String
'半角英数字以外があればエラーを返す
Dim RE, mchItems
Dim strPattern As String
Dim idx As Integer
If trg <> "" Then
Set RE = CreateObject("VBScript.RegExp")
strPattern = "[^0-9A-Z]"
With RE
.Pattern = strPattern
.IgnoreCase = True
.Global = True
Set mchItems = .Execute(StrConv(trg.Value, vbNarrow))
If mchItems.Count > 0 Then
MyFunc2 = "Error"
End If
End With
Set RE = Nothing
End If
End Function
お礼
ありがとうございます。 仕様が変わってしまい、また新たな問題が発生してしまいました・・ また行き詰ったらご教授ねがうやもしれません。 今回はとても勉強になりました!