2014-10-16 34 views
0

我有多張工作表,我想在一張工作表中複製「A2」,並在其他工作表中粘貼該值(或單元格中包含的公式)。我使用此代碼,但VBA highligts黃色「cell.Select」行。 如何解決它,你知道嗎?VBA,如何爲本書所有表中的有效範圍設置名稱?

Sub test() 

Set cell = Range("a2") 

cell.Select 
Selection.Copy 

Sheets("one").Activate 
cell.Select 
ActiveSheet.Paste 

Sheets("two").Activate 
cell.Select 
ActiveSheet.Paste 

End Sub 

感謝 尼古拉

回答

0

當你設置單元格給定的範圍內,你不需要選擇它。相反,你可以參考它。如果您還設置工作表對象,您希望最終將其粘貼到,上述然後可以寫得更緊湊和直接的方式,而不會選擇:

Sub test() 

    Set cell = Range("A2") 'implicit reference to activesheet in activeworkbook 

    Set ws1 = Sheets("one") 'requires that you have a sheet named "one" in the activeworkbook 
    Set ws2 = Sheets("two") 'requires that you have a sheet named "two" in the activeworkbook 

    'assign the value to somewhere in the ws1 and ws2 
    ws1.Range("A2") = cell 
    ws2.Range("A2") = cell 

End Sub 

編輯:使用複製

版,保留公式

Sub test() 

    Set cell = Range("A2") 'implicit reference to activesheet in activeworkbook 

    Set ws1 = Sheets("one") 'requires that you have a sheet named "one" in the activeworkbook 
    Set ws2 = Sheets("two") 'requires that you have a sheet named "two" in the activeworkbook 

    'assign the value to somewhere in the ws1 and ws2 
    cell.Copy Destination:=ws1.Range("A2") 
    cell.Copy Destination:=ws2.Range("A2") 


End Sub 
0
Sub test() 
    Dim cl As String 
    cl = Range("a2").Address 
    Range(cl).Copy Destination:=Sheets("one").Range(cl) 
    Range(cl).Copy Destination:=Sheets("two").Range(cl) 
End Sub 
相關問題