やり方
参照設定に『Microsoft Excel 16.0 Object Library』追加。
サンプル
Dim excel_ As New Excel.Application
Dim excel_sheet_ As Excel.Worksheet
'バックグラウンドで起動
excel_.Visible = False
excel_.UserControl = False
'Accessファイルと同じフォルダーにあるtes.xlsxが対象
excel_.Workbooks.Open FileName:=CurrentProject.Path & "\tes.xlsx"
'一番左のシートのみを選択状態に
Set excel_sheet_ = excel_.Worksheets(1)
excel_sheet_.Select Replace:=True
'『先に表示形式を設定して値は後』という順番にした方がいい。
'でないと本当は『12345678901234567890』という文字列にしたいのに、
'『1234567E+19』となってしまったりする。
'1行1列目のセル。
excel_sheet_.Cells(1, 1).NumberFormatLocal = "G/標準"
excel_sheet_.Cells(1, 1).Value = "12345678901234567890"
'2行1列目のセル。
excel_sheet_.Cells(2, 1).NumberFormatLocal = "@" '文字列
excel_sheet_.Cells(2, 1).Value = "12345678901234567890"
'3行1列目のセル。
excel_sheet_.Cells(3, 1).NumberFormatLocal = "#,##0" '数値
excel_sheet_.Cells(3, 1).Value = "12345678901234567890"
'4行1列目のセル。
excel_sheet_.Cells(4, 1).NumberFormatLocal = "yyyy年mm月dd日" '日付
excel_sheet_.Cells(4, 1).Value = "2023/07/09"
'Excelファイル保存してExcelアプリケーション終了。
excel_.Workbooks(1).Close SaveChanges:=True
excel_.Quit
実行前のエクセルファイルは、下記のようにシートを作っただけの状態。
値の設定は後がいい
下記のように 値を設定 ⇒ 表示形式を設定 とやると…
上記サンプルの一部を抜粋して処理順を変えたもの
'2行1列目のセル。
excel_sheet_.Cells(2, 1).Value = "12345678901234567890"
excel_sheet_.Cells(2, 1).NumberFormatLocal = "@" '文字列
下記のようになってしまう。
『1.23E+19』のような表示は嫌で文字列にしたのに、意図した結果になっていない。
参考サイトさん
バージョン
Windows 10 Pro 22H2 19045.3031
Microsoft Access for Microsoft 365 MSO (バージョン 2304 ビルド 16.0.16327.20200) 32 ビット
Microsoft Excel for Microsoft 365 MSO (バージョン 2304 ビルド 16.0.16327.20200) 32 ビット