繁体   English   中英

VBA:根据单元格值从选定的工作簿中复制粘贴

[英]VBA: copy paste from selected workbooks based on cell value

我想根据单元格值从选定的不同工作簿中复制数据,并将其粘贴到一个工作簿中

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称之为,您将x声明为工作表

Dim x As Worksheet

但您正在尝试将其设置为等于字符串

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

除了作为工作簿外,您还使用W执行相同的操作

也许尝试像

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

如果cells(2,1)中的值不是数字,则将出现类型不匹配错误。

顶部的这部分将给您一些问题

enter code here

这可能更适合您在评论中提到的内容:

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

尝试以下操作:在各个点使用Debug.Print可以更好地了解您的代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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