你是否可以在excel VBA代码中使用同名的工作表,但是在不同的工作簿中?

我的问题是,我有一个模板文件(月度报告)与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 

您将不得不移动一些代码,以便首先定义每个工作簿,然后使用这些工作簿对象来定义每个工作簿。

 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 

由于您定义(如上所述)ws是wb中的工作表,因此您不需要With wb wb。 此外,一个With ws … End With块定义了单元格的父级工作表,所以ws.cells是多余的; 只是.cells会做的。

正确缩进你的代码将很容易find这些小错误。