VBA PasteSpecial Transpose给出应用程序定义或对象定义的错误(1004)

时间:2018-08-09 03:00:53

标签: excel vba excel-vba

我正在尝试从CSV文件复制整列(减去标题)并将其转置粘贴到我的excel文件中。

“运行时错误'1004':应用程序定义的错误或对象定义的错误(1004)”在我尝试运行粘贴转置操作的最后一行进行了标记,但我不知道为什么?

代码如下:

Sub UpdateData()

Dim LastRow_1 As Long      ' Set up variable                                                                           
LastRow_1 = Workbooks("ProconData").Worksheets(1).Cells(Rows.Count,1).End(xlUp).Row ' Find last non-blank row


Dim CopyRange_1 As Range      ' Set up variable  
Set CopyRange_1 = Workbooks("ProconData").Worksheets("ProconData").Range("A2").Resize(LastRow_1, 1)  ' Define copy range

Dim PasteRange_1 As Range      ' Set up variable  
Set PasteRange_1 = Workbooks("TBM Ground Condition 
Record").Worksheets("RECORD").Range("LV4") '.Resize(4, 334 + LastRow_1) ' Define paste range

Workbooks("TBM Ground Condition Record").Worksheets("RECORD").Range(PasteRange_1).PasteSpecial Transpose:=True, Paste:=xlPasteValues  ' Transpose & paste data

End Sub

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

只是替代:

Workbooks("TBM Ground Condition Record").Worksheets("RECORD").Range(PasteRange_1).PasteSpecial Transpose:=True, Paste:=xlPasteValues  ' Transpose & paste data

具有:

CopyRange_1.Copy ' copy the range to be copied
PasteRange_1.PasteSpecial Transpose:=True, Paste:=xlPasteValues  ' Transpose & paste data ' paste the copied range to the one set for pasting

因为:

  1. 您没有复制任何内容
  2. 您已经将PasteRange_1设置为Range对象,因此您可以直接将其用作Range引用。虽然Range对象不能是Range()对象本身的Range属性的参数...(您可以看看the documentation

顺便说一句,您的代码假定“ ProconData”工作簿的第一个工作表被命名为“ ProconData”,但不一定总是正确的

您最好通过其名称引用所需的工作表,然后进行更改:

LastRow_1 = Workbooks("ProconData").Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row '

收件人:

LastRow_1 = Workbooks("ProconData").Worksheets("ProconData").Cells(Rows.Count, 1).End(xlUp).Row '

答案 1 :(得分:0)

尝试以下

Sub UpdateData()
    Dim LastRow_1 As Long      ' Set up variable
    LastRow_1 = Workbooks("ProconData").Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row ' Find last non-blank row
    Dim CopyRange_1 As Range      ' Set up variable
    Set CopyRange_1 = Workbooks("ProconData").Worksheets("ProconData").Range("A2").Resize(LastRow_1, 1)  ' Define copy range
    CopyRange_1.Copy
    Workbooks("TBM Ground Condition Record").Worksheets("RECORD").Range("LV4").PasteSpecial Transpose:=True  '.Resize(4, 334 + LastRow_1) ' Define paste range
End Sub