|
- Private Sub CommandButton2_Click()
- Dim SH As Worksheet, rg As Range
- Dim lngRows As Long
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String
-
- Set SH = Sheets("Sheet1")
- Set rg = SH.Range("A2") '数据集载入的起始区域
- lngRows = Sheet1.Range("A" & Rows.Count).End(xlUp).Row 'A列最后非空单元格的行号
- '''''''''''''''''''''''''''''''''''''''''''''''''''
- '这一整段是 ADO的调用方式,不解释了。主要是根据不同的EXCEL版本,处理连接字符串
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- strPath = ThisWorkbook.FullName
- Select Case Application.Version * 1
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & strPath
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
- Conn.Open strConn
- '''''''''''''''''''''''''''''''''
- 'SQL语句的含义
- '从sheet1表中,找到 【电话】字段长度为7或11 的,并根据【单位】和【电话】两个字段进行去重
- strSQL = "SELECT 单位,电话 " & _
- "FROM [Sheet1$A1:B" & lngRows & "] " & _
- "WHERE (Len(电话) = 7 or Len(电话) =11) " & _
- "Group By 单位,电话;"
- '''''''''''''''''''''''''''''''''''''''''
- Rst.Open strSQL, Conn, 3, 1
-
- '清除原有的数据
- Sheet1.Range("A2:B" & lngRows).ClearContents
- '从前面设定的起始区域,载入数据集
- rg.CopyFromRecordset Rst
- Set Rst = Nothing
- Set Conn = Nothing
- End Sub
复制代码 |
|