简体   繁体   中英

VBA - Copy and paste into multiple workbooks if cell = "Y"

EDIT: I edited the code so I can work on one issue at a time. Can someone help me understand why this program will only open the first workbook listed in this part of the code? Whichever workbook is listed first (a, b, c, etc.) will open, and the others cause an error (unable to find filepath or workbook).

Set x = Workbooks.Open(Range("J5").Value)
Set a = Workbooks.Open(Range("J6").Value)
Set b = Workbooks.Open(Range("J7").Value)
Set c = Workbooks.Open(Range("J8").Value)

ORIGINAL POST: I'm trying to write some code to do the following:

If a cell says "Y", then open workbooks x, a, b, c, and copy data from workbook x and paste into workbooks a, b, and c.

This will then check to see if another cell says "Y" and repeat the process with another set of workbooks.

I'm having difficulty with two things. First, I would like to open workbooks based on a filepath name that is in a cell. For instance, I can get the workbooks to open if I use set x = workbooks.open ("file path name here") but, if I instead put the filepath name in cell "A1" and try set x = workbooks.open ("A1") the macro won't work. Second, I have no idea how to get the code to skip over the operation if a certain cell isn't labeled "Y". You can see my attempt in the code but I tried several other things and keep running into issues.

The code I'm linking is just a sample, as my goal is to have this cycle through about 6 primary workbooks, each of the primary will then be copy and pasted into 3-5 sub workbooks.

Thanks in advance for any help on this!!

Sub Foo()
Dim x As Workbook

Dim a As Workbook
Dim b As Workbook
Dim c As Workbook

Dim vals As Variant

'## Open workbooks:
Set x = Workbooks.Open(Range("J5").Value)
Set a = Workbooks.Open(Range("J6").Value)
Set b = Workbooks.Open(Range("J7").Value)
Set c = Workbooks.Open(Range("J8").Value)

'Store the value in a variable:
vals = x.Sheets("Processed Summary").Range("M5:M63").Value

'Use the variable to assign a value to the other file/sheet:
a.Sheets("Processed Summary").Range("L5:L63").Value = vals
b.Sheets("Processed Summary").Range("L5:L63").Value = vals
c.Sheets("Processed Summary").Range("L5:L63").Value = vals

'Close Workbooks:
'x.Close
'a.Close
'b.Close
'c.Close

End Sub

You need to specify from where Range is originating. When code is trying to open second workbook "Set a = Workbooks.Open(Range("J6").Value)" it pulls Range out of cell J6 in workbook x as it is currently active workbook.

Try changing to: "Set a = Workbooks.Open(Workbooks("name.xls").Worksheets("Sheet1").Range("J6").Value)"

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