LoginSignup
1
1

More than 3 years have passed since last update.

エクセルマクロ(Excel VBA)でエクセルのデータを別のエクセルに転記する

Last updated at Posted at 2020-01-30

エクセルファイルのセルの値を別のエクセルファイルのセルにコピーするマクロを組んだのでシェアします。
使いどころは多いのに意外とネット上にサンプルソースが無くて困るんですよね。
コピペしてすぐに使えます。後はファイル一覧を取得してループ処理を組めば立派なシステムになるはずです。
サンプルでは、D:\Document\hogehoge.xlsxのSheet1のA1セルをコピーし、D:\Document\piyopiyo.xlsxのSheet1のB2セルに貼り付けしています。

Sub Execute()
    ' コピー元ファイルのパス
    Dim SourceFilePath As String
    SourceFilePath = "D:\Document\piyopiyo.xlsx"

    ' コピー先ファイルのパス
    Dim DestinationFilePath As String
    DestinationFilePath = "D:\Document\hogehoge.xlsx"

    ' コピー元のファイルを開く
    OpenOrActiveWorkBook (SourceFilePath)

    ' コピー先のファイルを開く
    OpenOrActiveWorkBook (DestinationFilePath)

    ' コピー元セル.Copy コピー先セル
    Workbooks(PathToFileName(SourceFilePath)).Worksheets("Sheet1").Range("A1").Copy _
    Workbooks(PathToFileName(DestinationFilePath)).Worksheets("Sheet1").Range("B2")

    ' コピー元のブックを閉じる
    Workbooks(PathToFileName(SourceFilePath)).Close

End Sub
' ファイルパスからファイル名を抜き出す
Function PathToFileName(Path As String)
    Dim PathName As String, FileName As String, pos As Long
    pos = InStrRev(Path, "\")
    PathName = Left(Path, pos)
    FileName = Mid(Path, pos + 1)
    PathToFileName = FileName
End Function

OpenOrActiveWorkBook関数はこちらの記事を参照してください
エクセルマクロ(Excel VBA)でExcelブックを開きアクティブにする

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