把Excel当成数据库操作

来源:互联网 发布:iso下载软件 编辑:程序博客网 时间:2024/04/28 14:54

近日老弟有个需求,要从excel中筛选数据出来。他只需要把筛选出来的数据放到另外一个Sheet里就行了。我的想法是用VBA 或者 c++。 c++是个人喜好,VBA是Office默认支持的,之间没有用过。于是Google了一把,发现还挺简单的,代码直接粘来用。用的是VBA 和 ODBC,微软自己的一套东西兼容性真是好。

事先当然是要有一个存了数据的excel文件
示例数据:

Emp IdName AgeDept 1Sumit20IT 2Raghav 13CS 3Gaurav 20MS 4Neel 30EEE 5Nemish 25IT 6Harish 22IT 7Bharath 21EEE 8Rishab 23Civil 9Gagan 27IT 10Abhishek 31Art

主要步骤:

  1. 设置目标文件为数据源 DSN
    64位系统注意”ODBC driver could not be found”,调用正确的位置设置数据源[1][2] ,如 windows 7 64位使用:
    c:\windows\sysWOW64\odbcad32.exe

  2. 打开VB编辑器
    我是从developer[3]标签打开的。Excel Options -> Popular -> Show Developer tab in Ribbon

  3. 执行得出结果

下面的代码就可以了,都是数据库操作的常规代码:
目的是把Sheet1 里 A1到Z500里 Dept 为 ‘IT’ 的行筛选出来放到Sheet2中

Sub ReadDB()Dim mainWorkBook As WorkbookDim intRowCounterSet mainWorkBook = ActiveWorkbookintRowCounter = 2mainWorkBook.Sheets("Sheet2").Range("A2:Z100").ClearSet Connection = CreateObject("ADODB.Connection")Connection.Open "DSN=SumitODBC"strQuery = "SELECT * FROM [Sheet1$A1:Z500] where Dept = 'IT'"Set resultSet = Connection.Execute(strQuery)Do While Not resultSet.EOF    mainWorkBook.Sheets("Sheet2").Range("A" & intRowCounter).Value = resultSet.Fields("Emp Id").Value    mainWorkBook.Sheets("Sheet2").Range("B" & intRowCounter).Value = resultSet.Fields("Name").Value    mainWorkBook.Sheets("Sheet2").Range("C" & intRowCounter).Value = resultSet.Fields("Age").Value    mainWorkBook.Sheets("Sheet2").Range("D" & intRowCounter).Value = resultSet.Fields("Dept").Value    intRowCounter = intRowCounter + 1  resultSet.movenextLoopresultSet.CloseEnd Sub

可以把代码保存成宏。我的结果是:
我的结果

当然也有用 csv 的,导出为 csv 再操作。比如 ref [4], 如果 用MFC的话 还有 CDatabase Class, CDaoDatabase Class 可以研究下。

[1]https://excel-macro.tutorialhorizon.com/vba-excel-make-excel-file-as-odbc-sourcedatabase-using-microsoft-excel-driver/
[2]https://support.microsoft.com/en-us/kb/2721825
[3]https://support.office.com/en-us/article/Show-the-Developer-tab-or-run-in-developer-mode-1b4a8529-3094-432a-9a7f-53935089e5ed
[4] http://www.cplusplus.com/forum/windows/28103/
[5]http://excel-macro.tutorialhorizon.com/vba-excel-read-excel-workbook-as-database-using-odbc-source/

0 0
原创粉丝点击