我是VBA的新手。
将数据从一个工作簿中的列转移到另一个工作簿中,因为行会抛出错误。尝试了Stack Overflow和其他地方的建议但没有成功。
错误运行时错误1004 - > Range类的PasteSpecial方法失败
码:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Workbooks.Open (FilePath & MyFile), Editable:=True
Dim SourceRange As Range
Set SourceRange = ActiveSheet.Range("E6:E7")
SourceRange.Copy
ActiveWorkbook.Close SaveChanges:=True
'Back to calling file - here.xlsm and pasting both values in single row (for e.g. A2 and B2)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Dim targetRange As Range
Set targetRange = ActiveSheet.Cells(erow, 1)
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
MyFile = Dir
Loop
End Sub
这是因为您不能同时执行这两个值并同时进行转置。
试试这个:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
Dim swb As Workbook
Dim twb As Workbook
Set twb = ThisWorkbook
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Change "Sheet1" below to the actual name of the sheet
erow = twb.Sheets("Sheet1").Cells(twb.Sheets("Sheet1").Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Set swb = Workbooks.Open(FilePath & MyFile)
'assign values
twb.Sheets("Sheet1").Cells(erow, 1).Resize(, 2).Value = Application.Transpose(swb.ActiveSheet.Range("E6:E7").Value)
'close
swb.Close SaveChanges:=True
MyFile = Dir
Loop
End Sub
这似乎有效:它是一个更简单的例子,同样的东西复制/粘贴方法只适用于活动对象(如,工作表,范围等),所以你需要激活一个,然后另一个,
Sub tst1()
Dim inbook, outbook As Workbook
Dim inSheet, outSheet As Worksheet
Dim inRange, outRange As Range
Set inbook = Application.Workbooks("temp1.xlsx")
Set outbook = Application.Workbooks("temp2.xlsx")
Set inSheet = inbook.Worksheets("sheet1")
Set outSheet = outbook.Worksheets("sheet1")
inSheet.Activate
Set inRange = ActiveSheet.Range("a1:b4")
inRange.Copy
outSheet.Activate
Set outRange = ActiveSheet.Range("a1:d2")
outRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub