【发布时间】:2018-06-11 17:09:12
【问题描述】:
Excel 表格布局
问题:
我必须从两张纸的第一列中找到所有字符串的超集。这些可以存在于一张或两张纸中。根据存在的字符串,将该字符串复制到第三张纸上。然后从一个或两个工作表中复制下一列中的数据。然后找出区别。重复。如果两个工作表中都存在字符串,则此代码有效。如果第一列中的字符串不存在于其中一个或两个中,我该如何使其工作?我想包含两张表中的所有数据。
这是代码:
Sub Macro5()
'
' Macro5 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
Dim dict As Scripting.Dictionary
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("sheet3")
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
'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
If ws1.Cells(rowy, 1) = ws2.Cells(rowy, 1) Then
ws3.Cells(rowy, 1) = ws1.Cells(rowy, 1)
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
ws3.Cells(rowy, Coli3 + 2) = Format((ws1.Cells(rowy, coli).Value) - (ws2.Cells(rowy, coli).Value), "#,##0")
Else
ws3.Cells(rowy, 1) = ws1.Cells(rowy, 1)
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).Value = 0 'copy sheet 2 to the right spot of sheet 3
ws3.Cells(rowy, Coli3 + 2) = Format((ws1.Cells(rowy, coli).Value) - (ws2.Cells(rowy, coli).Value), "#,##0")
End If
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
Next coli 'move to next column on ws1, ws2
End Sub
请帮忙。
【问题讨论】:
-
您关心的是确保工作表 1 或工作表 2 中是否缺少某个值以便继续进行比较?可以办到。 !st 我们需要在每次移动处理列时找到工作表 1 的最大行数和工作表 2 的最大行数(也许它们每次的长度都不相同),然后我们使用较大的 # 作为循环计数器。我们在其中放置一个 if 语句,如果一个或另一个为空,只需将其设为 0,在这种情况下,差异将始终是非空单元格(+ 或 -),或者我们可以说“No diff”或“missing” 1”或“缺少 2”,以后可以修改。
-
我对你使用字符串有点困惑,当它看起来是数字并且你正在确定数学差异时。确定字符串中的差异是一个非常不同的概念,在字符串中搜索字符串并报告找到的字符串前后的字符差异。 . .您正在使用数字,即使它们被读取为字符串(例如从访问读取中),您仍然可以将它们用作数字。对吗?