简体   繁体   中英

VBA: Copy data from another workbook, based on cell value of current workbook

Currently I have a workbook that loops through workbooks in the same folder as it, end copies data from specific cells back to the master workbook. If I want to change to cells from where the code copies cells, I'll have to change this value in the code.

However, I have co-workers who needs to use this sheet aswell, to collect data from other workbooks. – So I need to make this use friendly. What I want to do, is to have the code read a cell value in the masterworkbook, and use this cell value as the cell that it copies from.

Example:

If I type “B3” in the masterworkbook cell A1 and run the macro, the macro will copy data from the originsheet B3, into the first cell of the masterworkbook. Does anyone have any idear how to accomplish this?

Or something like:

.Cells(1).Value = originsheet.Range(Range("CellValue from destinationsheet A1").Value).Value

Here is the code I use:

    Sub Consolidate()

  Dim wkbkorigin As Workbook
  Dim originsheet As Worksheet
  Dim destsheet As Worksheet
  Dim ResultRow As Long
  Dim Fname As String
  Dim RngDest As Range


    Set destsheet = ThisWorkbook.Worksheets("Sheet1")
    Set RngDest = destsheet.Cells(Rows.Count, 1).End(xlUp) _
                       .Offset(1, 0).EntireRow
    Fname = Dir(ThisWorkbook.Path & "/*.xlsx")

    'loop through each file in folder (excluding this one)
    Do While Fname <> "" And Fname <> ThisWorkbook.Name

        If Fname <> ThisWorkbook.Name Then

            Set wkbkorigin = Workbooks.Open(ThisWorkbook.Path & "/" & Fname)
            Set originsheet = wkbkorigin.Worksheets(1)

            With RngDest
                .Cells(1).Value = originsheet.Range(Range("A1").Value).Value
                .Cells(2).Value = originsheet.Range(Range("A2").Value).Value
                .Cells(3).Value = originsheet.Range(Range("A3").Value).Value
                .Cells(4).Value = originsheet.Range(Range("A4").Value).Value
                .Cells(5).Value = originsheet.Range(Range("A5").Value).Value
            End With

            wkbkorigin.Close SaveChanges:=False   'close current file
            Set RngDest = RngDest.Offset(1, 0)

        End If

        Fname = Dir()     'get next file
    Loop
End Sub 

And a picture of what i mean, in case im unclear: enter image description here

I am sorry, but I believe you haven't made yourself clear. However, you may be trying to get something like this (correct me if I'm wrong):

destinationsheet.Range("A1") = originsheet.Range(destinationsheet.Range("A1"))

This will make the value in your Master Workbook be substituted by the content in cell address of the other worksheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM