0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【VBA】Splitを使って"100-103" を "100 101 102 103" に分割!!

Last updated at Posted at 2023-02-16

このような文字列を分割するには、VBAのSplit関数を使用することができます。Split関数は、指定した区切り文字で文字列を分割し、配列として返します。例えば、"100-103" をハイフン(-)で分割する場合は、以下のように記述することができます。

Dim str As String
Dim arr() As String

str = "100-103"
arr = Split(str, "-")

For i = 0 To UBound(arr)
    Debug.Print arr(i)
Next i

このコードを実行すると、"100-103" が "-" で分割され、配列 arr に "100", "103" の2つの要素が含まれることになります。配列の各要素を取得するには、For文を使用して配列をループ処理することができます。

次に、ハイフンで区切られた範囲内の数値をすべて含む文字列を作成するために、配列内の数値をループ処理して新しい文字列を作成します。例えば、以下のように記述することができます。

Dim str As String
Dim arr() As String
Dim i As Long
Dim result As String

str = "100-103"
arr = Split(str, "-")

For i = CLng(arr(0)) To CLng(arr(1))
    result = result & " " & CStr(i)
Next i

result = Trim(result)

MsgBox result

このコードでは、配列 arr の最初の要素を開始値、最後の要素を終了値として、For文を使用して数値をループ処理しています。ループ内では、result変数に数値を追加していき、最後にTrim関数を使用して不要な空白を削除しています。結果として、"100 101 102 103" という文字列が得られます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?