0

以下のコードは "data.xlsx" Excel ワークブックから実行され、Excel ワークブック ファイルを開いて "data.xlsx" からユーザーが開いた Excel ワークブックにデータをコピーするようにユーザーに求める必要があります。

Sub test()
    Dim ToSheet As Worksheet
    Dim FromBook As String
    Dim FromSheet As Worksheet
     '--------------------------------------------------------------------
    Set ToSheet = ActiveSheet
    FromBook = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx, All Files (*.*), *.*", 1, "Select Log File ")
    If FromBook = "False" Then Exit Sub
    Workbooks.Open FromBook
    Set FromSheet = ActiveSheet.Worksheets("Sheet1")
     '--------------------------------------------------------------------
     'Copy / Paste Data
   ToSheet.Activate
   DoColumnCopy "Apple", "Orange"
End Sub
'-------------------------------------------------------
'I need below code to work between the workbook, currently it 
'only works between the worksheet.

'Get data from FromColName and copy to ToColName
Sub DoColumnCopy(FromColName As String, ToColName As String)

    Dim rng As Range, rngCopy As Range, rng2 As Range

    Set rng = workbooks(1).Sheets("data").Rows(1).Find(What:=FromColName, LookIn:=xlValues, _
                                  LookAt:=xlWhole)
    If Not rng Is Nothing Then

        Set rngCopy = workbooks(1).Sheets("data").Range(rng).End(xlDown)

        Set rng2 = workbooks(2).Sheets("log").Rows(1).Find(What:=ToColName, LookIn:=xlValues, _
                                   LookAt:=xlWhole)

        If Not rng2 Is Nothing Then rngCopy.Copy rng2.Offset(1, 0)

    End If
End Sub

workbooks(2).sheets...ユーザーが開いたワークブックの名前を認識できるように、コードのこの部分を修正するにはどうすればよいですか? または複数のワークブックが開かれている場合は?

これを行うためのより良い方法があれば歓迎します
どうもありがとうございました!

4

1 に答える 1

1

他のワークブックのオブジェクトを宣言し、それに割り当てる必要があります。例(未テスト)

Sub test()
    Dim thisWb As Workbook, destWb As Workbook
    Dim ToSheet As Worksheet, FromSheet As Worksheet
    Dim FromBook As String

    '~~> Current workbook and the sheet
    Set thisWb = ThisWorkbook
    Set ToSheet = thisWb.ActiveSheet

    FromBook = Application.GetOpenFilename( _
    "Excel Files (*.xlsx), *.xlsx, All Files (*.*), *.*", 1, "Select Log File ")
    If FromBook = "False" Then Exit Sub

    '~~> This is how you store it in an object and then use it
    Set destWb = Workbooks.Open(FromBook)
    Set FromSheet = destWb.Worksheets("Sheet1")

    '
    '~~> Rest of your code
    '
End Sub
于 2013-09-23T22:31:11.923 に答える