2013-03-18 222 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 
相關問題