[英]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.
我想要做的是让代码读取masterworkbook中的单元格值,并将此单元格值用作它复制的单元格。
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. 如果我在masterworkbook单元格A1中键入“B3”并运行宏,宏将从原始表B3将数据复制到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. 这将使您的主工作簿中的值替换为另一个工作表的单元格地址中的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.