作者:绿色风
分类:
时间:2022-08-17
浏览:133
楼主 水星钓鱼 |
Q:如下图所示:
有多个工作表,每个工作表又有多个相同格式的单元格区域,现在需要在“汇总”工作表合并所有这些区域,并按照其中几个字段的顺序排序,该如何解决? A:由于涉及到多个工作表的多个单元格区域,用ADO时可以将每个单元格区域定义名称,然后再用SQL的联合查询这些定义的名称。 总的代码如下:- Option Explicit
- Public oName As Name
- Private sSql As String
- Public oWS As Worksheet
- Private arr() As String
- Private Sub CommandButton1_Click()
- Dim oRecrodset
- Dim sConStr As String
- Dim i As Integer
- sConStr = "Provider='Microsoft.Jet.OLEDB.4.0';Data Source=" & ThisWorkbook.FullName & ";Extended Properties='Excel 8.0;HDR=YES'"
- Call xyf_DeleteNames
- Call xyf_DefineName
- If ThisWorkbook.Names.Count = 0 Then
- MsgBox "没有数据要合并"
- Else
- Call xyf_GetSql
- Set oRecrodset = CreateObject("ADODB.Recordset")
- Set oWS = ThisWorkbook.Worksheets("汇总表")
- oWS.UsedRange.Clear
- With oRecrodset
- .Open sSql, sConStr
- For i = 1 To .Fields.Count
- oWS.Cells(1, i) = .Fields(i - 1).Name
- Next
- oWS.Cells(2, 1).CopyFromRecordset oRecrodset
- End With
- Set oRecrodset = Nothing
- End If
- End Sub
- Sub xyf_DefineName()
- Dim oRng As Range
- Dim i As Integer
- Dim s1st As String
- For Each oWS In ThisWorkbook.Worksheets
- If oWS.Name <> "汇总表" Then
- With oWS.Range("a1:a6366")
- Set oRng = .Find(what:="产品料号")
- s1st = oRng.Address
- Do
- If oRng.CurrentRegion.Rows.Count > 1 Then
- ThisWorkbook.Names.Add "rng" & i + 1, oRng.CurrentRegion
- ReDim Preserve arr(1 To i + 1)
- arr(i + 1) = "rng" & i + 1
- i = i + 1
- End If
- Set oRng = .FindNext(oRng)
- Loop While oRng.Address <> s1st
- End With
- End If
- Next oWS
- End Sub
- Sub xyf_GetSql()
- sSql = ""
- sSql = "select * from (select * from " & Join(arr, " union all select * from ") & ") order by 1,2,4,3"
- End Sub
- Sub xyf_DeleteNames()
- For Each oName In ThisWorkbook.Names
- oName.Delete
- Next oName
- End Sub
附件如下:
合并多个工作表的多个单元格区域.rar |
2楼 xyf2210 |
谢谢分享 |
3楼 老糊涂 |
谢谢分享 |
4楼 yytax2010 |
ADO好 |
免责声明
有感于原ExcelTip.Net留存知识的价值及部分知识具有的时间限定性因素,
经与ExcelTip.Net站长Apolloh商议并征得其同意,
现将原属ExcelTip.Net的知识帖采集资料于本站点进行展示,
供有需要的人士查询使用,也慰缅曾经的论坛时代。
所示各个帖子的原作者如对版权有异议,
可与本人沟通提出,或于本站点留言,我们会尽快处理。
在此,感谢ExcelTip.Net站长Apolloh的支持,感谢本站点所有人**绿色风(QQ:79664738)**的支持与奉献,特此鸣谢!
------本人网名**KevinChengCW(QQ:1210618015)**原ExcelTip.Net总版主之一