选项显式:你的朋友
这应该教会你始终使用Option Explicit。如果您一直在使用它,可能会发生以下情况 (Compile error: Variable not defined):
确定后:
您发现Row 有问题。
在更改为Rows 后,另一个Compile error: Variable not defined。确定后:
您发现a = 有问题。
在添加Dim a As Long 后,再添加一个Compile error: Variable not defined。确定后:
您发现i 有问题。
在添加Dim i As Long 后,再添加一个Compile error: Variable not defined。确定后:
你又发现Row 有问题了。
更改为Rows 后,另一个Compile error: Variable not defined。确定后:
您发现b = 有问题。
在添加Dim b As Long 后,再添加一个Compile error: Variable not defined。确定后:
您发现ActivateSheet 有问题。
改成ActiveSheet后终于Run-time error:
Debug之后:
Row 看起来又可疑了。
改成Rows后又是Run-time error:
在Debug之后:
您发现ActiveSheet.Paste 有问题,尤其是Paste。
改成ActiveSheet.PasteSpecial后另一个Run-time error:
Debug之后:
您发现Worksheets("Sale").Activate 有问题。
由于 Source.xlsx 处于活动状态,您可以考虑更改为 Workbooks("Purchase.xlsx").Worksheets("Sale").Activate,一切终于正常。还是这样?
守则
Option Explicit
Sub copycells()
Dim a As Long
Dim b As Long
Dim i As Long
With ThisWorkbook.Worksheets("Sale")
a = .Cells(.Rows.Count, 2).End(xlUp).Row
For i = 2 To a
If .Cells(i, 6).Value = "Parmesh" Then
.Rows(i).Copy
With Workbooks("Source.xlsx").Worksheets("Billdetails")
b = .Cells(.Rows.Count, 2).End(xlUp).Row
.Cells(b + 1, 1).PasteSpecial
End With
End If
Next
' If Purchase.xlsx and ThisWorkbook are the same then use the following:
'.Cells(1).Select
End With
Application.CutCopyMode = False
' If Purchase.xlsx and ThisWorkbook are not the same then use the following:
'Workbooks("Purchase.xlsx").Worksheets("Sale").Cells(1, 1).Select
End Sub
' Assuming that you need only values and that "Thisworkbook" is "Purchase.xlsx"
Sub copyCellsValues()
Const SourceBook As String = "Source.xlsx"
Const SourceSheet As String = "Billdetails"
Const MainSheet As String = "Sale"
Const MainColumn As Long = 6
Const Criteria As String = "Parmesh"
Dim Sale As Worksheet
Dim Bill As Worksheet
Dim a As Long
Dim b As Long
Dim i As Long
Set Sale = ThisWorkbook.Worksheets(MainSheet)
Set Bill = Workbooks(SourceBook).Worksheets(SourceSheet)
a = Sale.Cells(Sale.Rows.Count, 2).End(xlUp).Row
b = Bill.Cells(Bill.Rows.Count, 2).End(xlUp).Row + 1
For i = 2 To a
If Sale.Cells(i, MainColumn).Value = Criteria Then
Bill.Rows(b).Value = Sale.Rows(i).Value
b = b + 1
End If
Next
End Sub