LoginSignup
1
0

More than 3 years have passed since last update.

VBAで文字列結合を爆速にする方法

Last updated at Posted at 2019-08-16

はじめに

VBAで文字列を結合する時、このように&を使うことが多いと思います。

test.xlsx
Sub test()

    Dim str As String
    Dim i   As Long
    Dim tmp As String

    For i = 1 To 100000
        tmp = Rnd
        str = str & tmp
    Next

End Sub

この処理、私が試したところ、38秒かかりました。変数が大きくなるにつれてどんどん処理が遅くなってしまうようです。38秒って…結構辛いですよね。そこで他の書き方で試してみます。

まずは実行してみる

test.xlsx
Sub test2()

    Dim str As String
    Dim i As Long
    Dim tmp As String
    Dim counta As Long
    Dim tmp_len As Long

    counta = 1
    str = String$(1000000, 0)

    For i = 1 To 100000
        tmp = Rnd
        tmp_len = Len(tmp)
        Mid(str, counta, tmp_len + 1) = tmp
        counta = counta + tmp_len
    Next

    str = Mid(str, 1, counta)

End Sub

なんと…一瞬で終わります!

少しややこくなりましたが、やってることはとても簡単です。testプロシージャに追加したコードにコメントを入れて解説します。

test.xlsx
Sub test2()

    Dim str As String
    Dim i As Long
    Dim tmp As String

    '新しく追加した変数
    Dim counta As Long
    Dim tmp_len As Long

    'strを100万の空白文字(0)で埋め尽くす
    str = String$(1000000, 0)

    'strの何文字目まで実際のデータを入力したかを覚えておく
    counta = 1

    For i = 1 To 100000
        tmp = Rnd

        'tmpの文字数を取得する
        tmp_len = Len(tmp)

        '100万空白の中のcounta文字目からtmp_len文字分をtmpに入れ替える
        Mid(str, counta, tmp_len + 1) = tmp

        'データが入っている位置を更新する
        counta = counta + tmp_len
    Next

    '最後に後ろに残ってしまった大量の空白を削除する
    str = Mid(str, 1, counta)

End Sub

変数strに予め何文字入力する予定かを指定しないといけなくなりますが、この速度差は凄い!

1
0
1

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
1
0