使用vba如果表一中的a列和表二中的a列相同,则表二中的c列减表一中的c列输出到J列
时间: 2024-05-01 19:24:08 浏览: 42
VBA多列数据筛选输出提取表.txt
5星 · 资源好评率100%
可以使用 VBA 中的 For 循环和 If 语句来实现这个功能,以下是示例代码:
```vb
Sub CompareAndSubtract()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastRow1 As Long, lastRow2 As Long
Dim i As Long, j As Long
Dim a1 As String, a2 As String
Dim c1 As Double, c2 As Double
Set ws1 = ThisWorkbook.Worksheets("表一")
Set ws2 = ThisWorkbook.Worksheets("表二")
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow1 '从第2行开始比较
a1 = ws1.Cells(i, "A").Value
c1 = ws1.Cells(i, "C").Value
For j = 2 To lastRow2
a2 = ws2.Cells(j, "A").Value
If a1 = a2 Then '如果两个表格的 A 列相同
c2 = ws2.Cells(j, "C").Value
ws2.Cells(j, "J").Value = c2 - c1 '计算并输出到 J 列
End If
Next j
Next i
End Sub
```
请将代码中的表格名称替换为你自己的表格名称,并将代码复制到 VBA 编辑器中的模块中运行即可。
阅读全文