2013-05-31 32 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

相关问题