Excel VBA:将数据从一个工作簿中的列转换为另一个工作簿中的行

时间:2015-12-21 17:40:07

标签: excel vba rows transpose

我是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

2 个答案:

答案 0 :(得分:1)

这是因为您不能同时执行这两个值并同时进行转置。

试试这个:

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

答案 1 :(得分:1)

这似乎有效: 它是一个更简单的例子,做同样的事情 复制/粘贴方法仅适用于活动对象(例如,工作表,范围等) 所以你需要激活一个,然后激活另一个,

 self.collectionView.contentInset = UIEdgeInsetsMake(64.0f, 0.0f, 49.0f, 0.0f);