2013-05-31 138 views
3

我真的很陌生,在VBA中編程時遇到了這個代碼的問題,我試圖編寫它。我希望代碼能夠找出未使用的A列中的第一行,然後將數據從工作表的不同部分複製並粘貼到該行中。對象'_Global'的'範圍'當selectng範圍失敗時出錯

Sub CopyandPaste() 


Dim RowLast As Long 

RowLast = ThisWorkbook.Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Row 

Set NewRange = ThisWorkbook.Worksheets("Sheet2").Cells(RowLast, 1) 

ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select 
Selection.Copy 

Range("NewRange").Select 
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
    :=False, Transpose:=False 

End Sub 

任何幫助將是非常有益的。

回答

1

試試這個代碼:

Sub CopyandPaste() 

    Dim RowLast As Long 

    ThisWorkbook.Activate 
    With Worksheets("Sheet2") 
     RowLast = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row 
     Sheets("Sheet1").Cells(8, "B").Copy Sheets("Sheet2").Cells(RowLast, 1) 
    End With 

End Sub 
1

我添加註釋到代碼解釋我所做的更改。

Sub CopyandPaste() 

    Dim RowLast As Long 
    Dim newRange As Range 

    'this works easier if I understand your intent right 
    'I generally use some large row number with Excel 2010 
    'You may ahve to make this smaller if you are in 03 
    RowLast = Sheets("Sheet2").Range("B99999").End(xlUp) + 1 

    'if you KNOW you have continuous data in this column (no spaces) 
    RowLast = Sheets("Sheet2").Range("B1").End(xldown) + 1 

    'this is slightly better way to do this 
    Set newRange = ThisWorkbook.Worksheets("Sheet2").Range("A" & RowLast) 

    'don't do this 
    'ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select 
    'Selection.Copy 

    'do this instead 
    Sheets("Sheet1").Range("B8").Copy 
    newRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
     :=False, Transpose:=False 

    'you were attempting to use a variable name (newrange) as a 
    'name of a named range in the Excel sheet 
    'use the variable range itself (as above) 

End Sub 
+0

非常感謝你的評論,他們幫了很多。當我嘗試運行你的代碼時,我得到一個'類型不匹配'的錯誤,它強調了這一行「RowLast = Sheets(」Sheet2「)。Range(」B99999「).End(xlUp)+ 1」。 – Velocibear

+0

@Velocibear如果你有舊版本的Excel,你將不需要使用99999.如果你有2003 Excel,因爲它的最大行數限制是65536,請試試65500.我還添加了另一個選項,如果你有數據沒有空白。 – enderland

+0

Downvoter謹慎解釋? – enderland

相關問題