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?

Excel VBA ファイルを開く

Posted at

はじめに

ファイルを開きます。

プロシジャーの説明

ByVal(値渡し)とByRef(参照渡し)を利用し、ファイルAとファイルBを開き各々の最終行を取得します。

サンプル1

Option Explicit
    Dim wbMy As Workbook
    Dim wbA As Workbook
    Dim wbB As Workbook
    Dim wsMy As Worksheet
    Dim wsA As Worksheet
    Dim wsB As Worksheet
    Dim wsAlastRow As Long
    Dim wsBlastRow As Long
    Dim fp1 As String
    Dim fp2 As String
    Dim fp1Sheetname As String
    Dim fp2Sheetname As String
    Dim fp1lastRetu As Byte
    Dim fp2lastRetu As Byte


Sub maindesu()
    '値渡し用。WorkbookOpenで渡すだけ
    fp1 = "C:\ALLlib\エクセルマクロ\練習0510A.xlsx"
    fp2 = "C:\ALLlib\エクセルマクロ\練習0510B.xlsx"
    fp1Sheetname = "データA"
    fp2Sheetname = "データB"
    fp1lastRetu = 2
    fp2lastRetu = 1
    
    '参照渡し用。WorkbookOpenで渡し結果値をもらう
    wsAlastRow = 0
    wsBlastRow = 0
    Set wsA = Nothing
    Set wsB = Nothing
    Set wbA = Nothing
    Set wbB = Nothing
    
    ' マクロが書かれているブック(このブック)を設定
    Set wbMy = ThisWorkbook
    
    Call WorkbookOpen(fp1, fp1Sheetname, fp1lastRetu, wsAlastRow, wbA, wsA)
    Call WorkbookOpen(fp2, fp2Sheetname, fp2lastRetu, wsBlastRow, wbB, wsB)
    
    ' A1セルの値を取得し、A2セルへペースト
    wsB.Range("A2").Value = wsA.Range("A1").Value
    ' ブックAをアクティブにする
    wbA.Activate
    ' シートAをアクティブにする
    wsA.Activate
    MsgBox wsAlastRow
    MsgBox wsBlastRow
End Sub


Function WorkbookOpen(ByVal filePas As String, ByVal sheeto As String, ByVal retu As Byte, _
                      ByRef RetwslastRow As Long, ByRef Retwb As Workbook, ByRef Retws As Worksheet)
'********************************************************************
'6ケの値は3ケがByValで3ケがByRef。ByRefは元のプロシジャーで使用
' ByVal(値渡し)呼び出し元の変数には影響を与えない
' ByRef(参照渡し)呼び出し元の変数が変更される
'********************************************************************

    ' ブックを設定(開いているブック名を指定)
    Set Retwb = Workbooks.Open(filePas) ' フルパスを指定
    
    ' シートを設定
    Set Retws = Retwb.Sheets(sheeto) ' シートAの名前を指定

    'wsの?列の最終行を取得
    RetwslastRow = Retws.Cells(Retws.Rows.Count, retu).End(xlUp).Row

End Function


おわり

ByVal(値渡し)とByRef(参照渡し)を利用するとスッキリしたソースが書けます

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?