【发布时间】:2017-12-27 18:34:28
【问题描述】:
我有两个不同的工作表。我必须从第一张纸上复制第一列(A)。根据第一列中的字符串,从第一列复制数据,从第一张表复制第二列(B),从第二张表复制第二列(B),然后找出两个复制列之间的差异。所有这些数据都将粘贴到新工作表中。重复该过程,从第一张表复制第三列(C),从第二张表复制第三列(C),然后找出差异。重复此过程直到最后一列。
如何使代码动态化,以便在工作表中查找第一列中的数据,然后从其他列中复制数据。
我能够在 WWC 的帮助下使这段代码工作,但是如何在第一列中查找数据然后复制值。
Sub Macro4()
'
' Macro4 Macro
'
'
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim coli As Double
Dim Coli3 As Double
Dim rowy As Double
Dim numCols As Double
Dim startRow As Double
Dim lastRow As Double
startRow = 6 'assuming data starts here
Coli3 = 2 ' start the columns out on ws3
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Set ws2 = ThisWorkbook.Worksheets("Sheet2")
Set ws3 = ThisWorkbook.Worksheets("Comparison")
Application.ScreenUpdating = False
ws3.Cells.Clear
ws1.Range("A1").EntireColumn.Copy Destination:=ws3.Range("A1")
'Find how many columns there are in sheet1 based on data in row 1
numCols = ws1.Cells(7, Columns.Count).End(xlToLeft).Column
For coli = 2 To numCols
'Find last Data row in the given column in sheet1
lastRow = ws1.Cells(ws1.Rows.Count, coli).End(xlUp).Row
For rowy = 6 To lastRow
ws3.Cells(rowy, Coli3) = Format(ws1.Cells(rowy, coli).Value, "#,##0") ' copy sheet 1 to the right spot of sheet 3
ws3.Cells(rowy, Coli3 + 1) = Format(ws2.Cells(rowy, coli).Value, "#,##0") 'copy sheet 2 to the right spot of sheet 3
'perform calculation and place in the right spot on sheet 3
If rowy = "6" Then
ws3.Cells(rowy, Coli3) = ws1.Cells(rowy, coli) & "-Sheet1" ' copy sheet 1 to the right spot of sheet 3
ws3.Cells(rowy, Coli3 + 1) = ws2.Cells(rowy, coli) & "-Sheet2" 'copy sheet 2 to the right spot of sheet 3
ws3.Cells(rowy, Coli3 + 2) = "Difference"
Else
ws3.Cells(rowy, Coli3) = Format(ws1.Cells(rowy, coli).Value, "#,##0") ' copy sheet 1 to the right spot of sheet 3
'ws3.Cells(rowy, Coli3).Font.Name = "Arial"
'ws3.Cells(rowy, Coli3).Font.Size = 8
ws3.Cells(rowy, Coli3 + 1) = Format(ws2.Cells(rowy, coli).Value, "#,##0") 'copy sheet 2 to the right spot of sheet 3
'ws3.Cells(rowy, Coli3 + 1).Font.Name = "Arial"
'ws3.Cells(rowy, Coli3 + 1).Font.Size = 8
ws3.Cells(rowy, Coli3 + 2) = Format((ws1.Cells(rowy, coli).Value) - (ws2.Cells(rowy, coli).Value), "#,##0")
'ws3.Cells(rowy, Coli3 + 2).Font.Name = "Arial"
'ws3.Cells(rowy, Coli3 + 2).Font.Size = 8
End If
Next rowy ' move to the next row on ws1, ws2, ws3
'Since we are placing 3 cols at a time in sheet 3 we increment differently
Coli3 = Coli3 + 3 '1 becomes 4, 4 becomes 7, 7 becomes 10 and so on
End Sub
【问题讨论】:
-
你试过什么?在线使用 VBA 的循环示例数不胜数。
-
我已经在这里发布了我的代码。它工作正常,但我无法将其放入 for 循环中。我无法定义范围内的数字来复制整个列
-
如果您的问题是动态引用范围,您可能需要考虑使用 Cells() .....见excelmatters.com/referring-to-ranges-in-vba
-
我试图用 ws1.Range.Cells(2).EntireColumn.Copy Destination 替换: ws1.Range("B1").EntireColumn.Copy Destination:=ws3.Range("B1") :=ws3.Range(2) ws1.Range(2, 1).EntireColumn.Copy Destination:=ws3.Range(2, 1) 它不起作用
-
正如 Fred 在 cmets 中提到的,使用
.Cells()这将完成您的任务