请教如何利用 Excel2003 vba宏,实现两个工作表之间的查询?

2024-11-14 23:54:50
推荐回答(4个)
回答(1):

你的意思是把sheet1中有而sheet2中没有的提取出来放在sheet3是吧?
这个很容易作到,到我百度空间去看下,用差集完成,
你得说明一下你的表有多少列?可说明提取的是什么内容?或把文件发过来,不明白的地方HI我
以下代码以A为序号、B列为姓名为例,用循环的方法来提取
Sub 提取sheet1独有的()
Dim arr1, arr2, Arr3()
Dim R&, R1&, x&, y&, i&
R = Sheet1.Range("A65536").End(xlUp).Row
R1 = Sheet2.Range("A65536").End(xlUp).Row
arr1 = Sheet1.Range("A1:B" & R).Value
arr2 = Sheet2.Range("A1:B" & R1).Value
For x = 1 To UBound(arr1)
For y = 1 To UBound(arr2)
If arr2(y, 2) = arr1(x, 2) Then
GoTo aaa
End If
Next y
i = i + 1
ReDim Preserve Arr3(1 To 2, 0 To i)
Arr3(1, i) = arr1(x, 1)
Arr3(2, i) = arr1(x, 2)
aaa:
Next x
Arr3(1, 0) = "序号"
Arr3(2, 0) = "姓名"
With Sheet3
.Columns("A:B").ClearContents
.Range("A1").Resize(UBound(Arr3, 2) + 1, 2) = Application.Transpose(Arr3)
End With
End Sub

回答(2):

Public Sub 比较输出不同行()
Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet
Dim c1 As Range, c2 As Range, c3 As Range
Dim c As Range, cc As Range, r&, t As Boolean, d, tmp

'----根据实际表格,设置下面的变量值-------
Set sh1 = Worksheets("sheet1") '表1
Set sh2 = Worksheets("sheet2") '表2
Set sh3 = Worksheets("sheet3") '表3
Set c1 = sh1.Range("A:B") '表1的数据位置
Set c2 = sh2.Range("A:B") '表2的数据位置
Set c3 = sh3.Range("A:B") '表3的数据位置,放置结果
t = True '默认使用表1中的序号,如果要建立新序号,改为 False
'----设置变量值结束-------

Set d = CreateObject("Scripting.Dictionary")
Set cc = Application.Intersect(c1.Columns(2), sh1.UsedRange)
For Each c In cc
If c <> "" Then d(c.Value) = c.Offset(0, -1).Value
Next
Set cc = Application.Intersect(c2.Columns(2), sh2.UsedRange)
For Each c In cc
If c <> "" Then
If d.Exists(c.Value) Then d.Remove (c.Value)
End If
Next
With c3
.EntireColumn.ClearContents '清空结果位置
tmp = c1.Rows(1) '写入 表头
.Rows(1) = tmp
tmp = d.keys '写入 姓名
.Columns(2).Cells(2, 1).Resize(d.Count, 1) = _
Application.WorksheetFunction.Transpose(tmp)
If t Then
tmp = d.items '写入 表1中的原序号
.Columns(1).Cells(2, 1).Resize(d.Count, 1) = _
Application.WorksheetFunction.Transpose(tmp)
Else
For r = 1 To d.Count '建立新的序号
.Cells(r + 1, 1).Value = r
Next
End If
End With
End Sub

回答(3):

要实现这一功能,对Excel来说,也并不难。 例如我们将光标定位到一个登记“那么如何对表格进行成组编辑呢?首先我们单击第一个工作表的标签名“Sheet1”

回答(4):

用Vlookup就能实现,非要VBA吗?