我的问题是我有一个455行的模板文件(每月报告)和一个DataDownload文件,其中行数变化。当没有区域和段的数据时,它被省略。在所有其他方面,这两个文件是相同的。即工作表名称相同。我的下面的代码只是从DataDownload覆盖模板中的信息。
Option Explicit
Sub copyanpaste()
Dim linecount As Long
Dim linecount2 As Long
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim wb As Workbook
Dim wb2 As Workbook
Dim region As String
Dim region2 As String
Dim segment As String
Dim segment2 As String
Dim i As Long
Set ws = Worksheets("3 REGION SEGMENT")
Set ws2 = Worksheets("3 REGION SEGMENT")
Set wb = Application.Workbooks("DataDownload")
Set wb2 = Application.Workbooks("Monthly Report - 201705")
linecount = 4
linecount2 = 4
For i = 1 To 455
With wb
With ws
region = ws.Cells(linecount, "B")
segment = ws.Cells(linecount, "D")
End With
End With
With wb2
With ws2
region2 = ws2.Cells(linecount2, "B")
segment2 = ws2.Cells(linecount2, "D")
End With
End With
If region = region2 And segment = segment2 Then
wb.Sheets("3 REGION SEGMENT").Cells(linecount2, "A").EntireRow.Copy Destination:=wb2.Sheets("3 REGION SEGMENT").Range("A" & linecount)
linecount = linecount + 1
linecount2 = linecount2 + 1
Else
linecount2 = linecount2 + 1
End If
Next i
End Sub
答案 0 :(得分:1)
您必须先移动一些代码,以便先定义每个工作簿,然后使用这些工作簿对象来定义每个工作簿中的工作表。
Set wb = Application.Workbooks("DataDownload")
Set wb2 = Application.Workbooks("Monthly Report - 201705")
Set ws = wb.Worksheets("3 REGION SEGMENT")
Set ws2 = wb2.Worksheets("3 REGION SEGMENT")
此外,您没有正确使用With ... End With块。此,
With wb
With ws
region = ws.Cells(linecount, "B")
segment = ws.Cells(linecount, "D")
End With
End With
......应该是,
With ws
region = .Cells(linecount, "B")
segment = .Cells(linecount, "D")
End With
您完全不需要With wb
,因为您定义(如上所述)是wb中的工作表。此外,使用ws ... End With块定义单元格的父工作表,因此ws.cells是多余的;只是.cells会做的。
正确缩进代码将大大有助于轻松找到这些小错误。