回答編集履歴

4

追記

2023/10/18 07:09

投稿

otn
otn

スコア86324

test CHANGED
@@ -34,3 +34,21 @@
34
34
  conv = s
35
35
  End Function
36
36
  ```
37
+
38
+ ## 追記2
39
+ 初期化も関数内部で行うように変更。
40
+ ```VBA
41
+ Function conv(s As String) As String
42
+ Static re As Object
43
+ If re Is Nothing Then
44
+ Set re = CreateObject("VBScript.RegExp")
45
+ re.Pattern = "[A-Za-z]+"
46
+ re.IgnoreCase = False
47
+ re.Global = True
48
+ End If
49
+ For Each Match In re.Execute(s)
50
+ Mid(s, Match.firstindex + 1, Match.Length) = StrConv(Match.Value, vbNarrow)
51
+ Next Match
52
+ conv = s
53
+ End Function
54
+ ```

3

サンプル改善

2023/10/18 04:40

投稿

otn
otn

スコア86324

test CHANGED
@@ -13,13 +13,13 @@
13
13
  ## 追記
14
14
  > グローバル変数?正規表現設定?専門用語が分からず回答がいまいちピンときません。
15
15
  > このコードをどこに配置したらいいんでしょうか?
16
- とのことなので、サンプルです。
16
+ とのことなので、サンプルです。ちょっと改善しておきました。
17
17
  正規表現という概念を知らないということなので、コードの意味が分からないと思いますが。
18
18
  ```VBA
19
19
  Dim re 'これがグローバル変数(VBA用語ではモジュールレベル変数)。モジュール内の全Sub/Functionから使える
20
20
  Sub メイン処理()
21
21
  Set re = CreateObject("VBScript.RegExp")
22
- re.Pattern = "[A-Za-z]"
22
+ re.Pattern = "[A-Za-z]+"
23
23
  re.IgnoreCase = False
24
24
  re.Global = True
25
25
 
@@ -29,7 +29,7 @@
29
29
  End Sub
30
30
  Function conv(s as String) as String
31
31
  For Each Match In re.Execute(s)
32
- Mid(s, Match.firstindex + 1, 1) = StrConv(Match.Value, vbNarrow)
32
+ Mid(s, Match.firstindex + 1, Match.Length) = StrConv(Match.Value, vbNarrow)
33
33
  Next Match
34
34
  conv = s
35
35
  End Function

2

サンプル追記

2023/10/18 04:30

投稿

otn
otn

スコア86324

test CHANGED
@@ -9,3 +9,28 @@
9
9
  Mid(s, Match.firstindex + 1, 1) = StrConv(Match.Value, vbNarrow)
10
10
  Next Match
11
11
  ```
12
+
13
+ ## 追記
14
+ > グローバル変数?正規表現設定?専門用語が分からず回答がいまいちピンときません。
15
+ > このコードをどこに配置したらいいんでしょうか?
16
+ とのことなので、サンプルです。
17
+ 正規表現という概念を知らないということなので、コードの意味が分からないと思いますが。
18
+ ```VBA
19
+ Dim re 'これがグローバル変数(VBA用語ではモジュールレベル変数)。モジュール内の全Sub/Functionから使える
20
+ Sub メイン処理()
21
+ Set re = CreateObject("VBScript.RegExp")
22
+ re.Pattern = "[A-Za-z]"
23
+ re.IgnoreCase = False
24
+ re.Global = True
25
+
26
+ ~~~~~
27
+ x = conv(x)
28
+ ~~~~~
29
+ End Sub
30
+ Function conv(s as String) as String
31
+ For Each Match In re.Execute(s)
32
+ Mid(s, Match.firstindex + 1, 1) = StrConv(Match.Value, vbNarrow)
33
+ Next Match
34
+ conv = s
35
+ End Function
36
+ ```

1

Excelでテストしたときのままだった

2023/10/17 07:02

投稿

otn
otn

スコア86324

test CHANGED
@@ -1,14 +1,11 @@
1
1
  多分、正規表現を使った方が早いです。
2
2
  ```VBA
3
+ s = "対象文字列"
3
4
  Set re = CreateObject("VBScript.RegExp")
4
5
  re.Pattern = "[A-Za-z]"
5
6
  re.IgnoreCase = False
6
7
  re.Global = True
7
- For i = 1 To 10
8
- s = Cells(i, 1).Value
9
- For Each Match In re.Execute(s)
8
+ For Each Match In re.Execute(s)
10
- Mid(s, Match.firstindex + 1, 1) = StrConv(Match.Value, vbNarrow)
9
+ Mid(s, Match.firstindex + 1, 1) = StrConv(Match.Value, vbNarrow)
11
- Next Match
10
+ Next Match
12
- Cells(i, 2).Value = s
13
- Next
14
11
  ```