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.

ChatGPTにExcelVBAを習ったら試行錯誤がぱねェ(テキストの読み込み他

Posted at

要約

ChatGPTにExcelVBAを習った。
テキストファイルの読み込みについて3つ方法を習った。最後の1個がうまくいった。

詳細

最初習ったのはInput$関数というのを使う。

    filePath = "C:\foo\bar.txt"
    fileNumber = FreeFile
    Open filePath For Input As fileNumber
    fileContent = Input$(LOF(fileNumber), fileNumber)
    Close fileNumber

しかしこれだとInput$関数において

 Run-time error '62':
  input past end of file

というエラーになる。
fileContentは""、LOF(fileNumber)はbar.txtの正しいファイルサイズ)。

次に習ったのはLine Inputを使う。

    filePath = "C:\foo\bar.txt"
    fileNumber = FreeFile
    Open filePath For Input As fileNumber
    Do Until EOF(fileNumber)
        Line Input #fileNumber, fileContent
    Loop
    Close fileNumber

正常に実行されるが、fileContentは累積されず、"The End"(foo.txtの末尾行)になる。

最後にバイナリーモードでOpenし、Getというのを使った。

    filePath = "C:\foo\bar.txt"
    fileNumber = FreeFile
    Open filePath For Binary As fileNumber
    fileContent = Space$(LOF(fileNumber))
    Get #fileNumber, , fileContent
    Close fileNumber

これだと上手く言った。
なんでやねん。

VBAのファイル読み込み処理は、環境やバージョンの差異、ファイルのエンコーディングなどにより挙動が変わることがあります。バイナリモードで読み込むことで、テキストファイルのエンコーディングに関わらず安定してファイルを読み込むことができる場合があります。

へぇー。

余談

もう1個、VBAモジュールを取得するということをやっていて、

Set vbComponent = destinationWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)

だとうまくいかない。
自分でウォッチ式を使って調べたら、Microsoft Excel VBAによって事前定義されているべきvbext_ct_StdModuleがemptyになっていたので、

        Set vbComponent = destinationWorkbook.VBProject.VBComponents.Add(1)

と数字リテラル1を指定したら動作した。

大変申し訳ありません。VBAエディタのバージョンや環境によって、vbext_ct_StdModule が正常に認識されないことがあります。ご指摘いただき、ありがとうございます。

おっしゃる通り、vbext_ct_StdModule が定義されていない場合は、数値リテラルを使用してモジュールを追加する方法が有効です。以下がその修正版のコードです。

だって。

感想

思ったより時間がかかってしまったが、懲りずにあれこれ方法を考えてくれるのはいいやつだなと思った。

(終わり)

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