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.

AccessのVBAでエクセルファイル操作時に1004エラー起きた時の対応

Last updated at Posted at 2023-01-20

現象

外部エクセルファイルを編集する処理。
(一番左のシートの特定セルに値をセットするなど)

下記の excel_sheet_.Select Replace:=True で例外。

Dim excel_ As New Excel.Application

'バックグラウンドでエクセルファイル開く。
excel_.Visible = False
excel_.UserControl = False
excel_.Workbooks.Open FileName:=CurrentProject.Path & "\test.xlsx"

'一番左のシートのみを選択状態に。
Dim excel_sheet_ As Excel.Worksheet
Set excel_sheet_ = excel_.Worksheets(1)
' ↓ ここで例外
excel_sheet_.Select Replace:=True

'セルに値セットするなど各種処理。

'エクセル保存して閉じる。
excel_.Workbooks(1).Close SaveChanges:=True
excel_.Quit

実行時エラー1004
Selectメソッドは失敗しました'_WorkSheet'オブジェクト

image.png

原因

一番左のシートが非表示になっている為。

下記のように再表示してあげればOK。

image.png

image.png

image.png

全シートが非表示になっていれば見た目で分かりやすい
でも、一部シートだけ非表示にされると分かりにくい。

残プロセスに注意

  1. エクセルファイルをバックグラウンドで開いて処理中に例外。
  2. AccessのVBE上で処理終了させる。
    Quit を呼び出さずに、強制的に処理中断させるような形)

だと、下記のように不要プロセスが残ってしまうので注意。
image.png

要はエクセルファイルが開きっぱなしの状態なので、いろいろ弊害あり。

バージョン

Windows 10 Pro 22H2 OSビルド 19045.2486
Microsoft Access for Microsoft 365 MSO (バージョン 2212 ビルド 16.0.15928.20196) 32 ビット
Microsoft Excel for Microsoft 365 MSO (バージョン 2212 ビルド 16.0.15928.20196) 32 ビット

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?