2013-03-18 223 views
1

我想复制工作表3的单元格区域(C1:Z1000)并将它们粘贴到工作表1的第一个空列(在第1行中)。在最后的线下块代码:source.Range个( “C:Z1000”)。复制destination.Cells(1,emptyColumn)在excel vba的第一个空列中复制粘贴范围

Sub CopyRange() 

Dim source As Worksheet 
Dim destination As Worksheet 
Dim emptyColumn As Long 

Set source = Sheets("Sheet3") 
Set destination = Sheets("Sheet1") 

'find empty Column (actually cell in Row 1)' 
emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlUp).Column 
If emptyColumn > 1 Then 
emptyColumn = emptyColumn + 1 
End If 

source.Range("C1:Z1000").Copy destination.Cells(1, emptyColumn) 

End Sub 
+1

您的代码是不合逻辑的。您检查sheet3的LAST列是否为空,如果不是,则取下NEXT列。当然哪个永远不会存在。 –

回答

0

试试这个:

emptyColumn = destination.Cells(1, destination.Columns.Count).End(xltoright).Column 

source.Range("C1:Z1000").Copy Destination:= Cells(1, emptyColumn) 

命名参数之后是冒号等于:=

您的结束码应该是:结束(xlToRight)

另一种方法是:

source.Range("C1:Z1000").Copy 
with destination 
    .cells(1,emptycolumn).select 
    .paste 
end with 

我希望帮助

菲利普

+0

仍然无法正常工作... – user2172916

+0

确定哪里出错?也许试试下面给出的第二个选项。此外,**是Sourece像工作表或工作簿,或范围对象** –

1

您是否尝试过单步调试代码?

如果你这样做,你会发现,下面一行将emptyColumns变量始终设置到最右列,无论哪个列用于:

emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlUp).Column 

通过添加1〜它和粘贴你尝试粘贴到不存在的列。每次都会给你一个错误。

而是,请尝试以下操作以查找最后使用的列。它从第一行中的最右侧一列搜索,去左边(如打字CTRL + LEFT),为了找到最后使用的列:

emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlToLeft).Column 

然后你就可以把它加1和糊。

+0

我认为最后一列是**。结束(xlToRight)。列** –

+3

不,这是设计。我开始到最右边('destination.Columns。计数“),然后向左走,所以我不会卡在中间的空列上,而右侧会出现更多使用的列。 :) –

2

我认为你的问题是你获得emptyColumn值的方式,正如其他人所建议的那样。这个工作对我来说:

Sub CopyRange() 

Dim source As Worksheet 
Dim destination As Worksheet 
Dim emptyColumn As Long 

Set source = Sheets("Sheet3") 
Set destination = Sheets("Sheet1") 

'find empty Column (actually cell in Row 1)' 
emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlToLeft).Column 
If emptyColumn > 1 Then 
emptyColumn = emptyColumn + 1 
End If 

source.Range("C1:Z1000").Copy destination.Cells(1, emptyColumn) 

End Sub 

你现在拥有它会拉的最后列中的工作表,粘贴到它的时候,这似乎引发的错误的方式。上述方法将拉第一个空列。也就是说,如果C列是空的,emptyColumn的值将是3

0

我发现这篇文章,修改它以符合我的需要。将粘贴转置

Sub Transpose_PasteModified() 

Dim source As Worksheet 
Dim destination As Worksheet 
Dim emptyColumn As Long 

Set source = Sheets("Sheet1") 
Set destination = Sheets("Sheet2") 
'Data Source 
source.Range("A3:C3").Copy 
'Gets Empty Column 
emptyColumn = destination.Cells(3, destination.Columns.Count).End(xlToLeft).Column 

'In order to avoid issues of first row returning 1 
'in this case #3 is the row so we're checking A3 
'If row changes then change A3 to correct row 

If IsEmpty(destination.Range("A3")) Then 
destination.Cells(3, 1).PasteSpecial Transpose:=True 
Else 
emptyColumn = emptyColumn + 1 
destination.Cells(3, emptyColumn).PasteSpecial Transpose:=True 
End If 

End Sub 
相关问题