简体   繁体   中英

VBA: copy paste from selected workbooks based on cell value

I want to copy data from selected different workbooks based on cell value and paste it to one single workbook

enter code here
Sub Ram_copypaste()
Dim w As Workbook
Dim A As String
Dim x As Worksheet
Dim j As Integer
Dim i As Integer
j = cells(2, 1).Value
A = "Portfolio"
B = ".xlsx"
For i = 1 To j
Set w = A & i & B
Set x = A & i
w.Worksheets("Download1").Range("A1:H14").Copy
Workbooks("TE copypaste.xlsx").x.cells(1, 1).PasteSpecial xlPasteValues
Next i
End Sub

Anil called it, you're declaring x as a worksheet

Dim x As Worksheet

but you're trying to set it equal to a string

A = "Portfolio"
For i = 1
Set x = A & i

You're also doing the same thing with W except as a workbook

Maybe try something like

set w = Workbooks.Open(<path>\<filename>)
set x = w.sheets(A & I)

If the value in cells(2,1) is non numeric you'll get a type mismatch error.

This piece at the top will give you some issues

enter code here

This might be more suited to what you mentioned in your comment:

Sub test()

Dim workBookPath As String, filename As String
Dim i As Long, j As Long
Dim awb As Workbook, w As Workbook
Dim x As Worksheet

Set awb = ActiveWorkbook

workBookPath = "C:\users\mt390d\Documents\Reports\"
    If IsNumeric(Cells(2, 1)) Then
        j = Cells(2, 1).Value
        Else: MsgBox ("Cell A2 must contain a number")
        Exit Sub
    End If

For i = 1 To j
    filename = Dir(workBookPath)
    If filename <> awb.Name Then
        Set w = Workbooks.Open(workBookPath & filename)
        Sheets("Download1").Copy awb.Sheets(1)
        Set x = ActiveSheet
        On Error Resume Next
            x.Name = "Portfolio" & i
        On Error GoTo 0
        w.Close
    End If
    filename = Dir()
Next i

End Sub

Try this: Use Debug.Print at various points to understand your code better.

Sub Ram_copypaste()
Dim w As Workbook
Dim A As String, B As String
Dim x As Worksheet
Dim j As Integer
Dim i As Integer

j = cells(2, 1).Value   'Use Debug.Print to check the value of J
A = "Portfolio"
B = ".xlsx"
For i = 1 To j
Set w = workbooks(A & i & B)   'Make sure you already have a workbook 
   'with the same name as A & i & B opened otherwise this will give error. If 
   'you don't have it opened but have it on your drive first open it and then set it.

set x = w.sheets(A & i)      'As suggested by Anil Kumar to avoid Type Mismatch error
w.Worksheets("Download1").Range("A1:H14").Copy
Workbooks("TE copypaste.xlsx").x.cells(1, 1).Select
Workbooks("TE copypaste.xlsx").x.cells(1, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Next i
End Sub

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