OK,同学们,今天我要跟各位聊的是:excel生成数据库表
公司保密条款,使用的是测试数据演示,嘿嘿,还是万年不变的妍妍叫我肉肉
角色1:源数据
角色2:导入模板(我会把它上传,到时候改成自己的就行)
反向生成数据库表起因:需求就给你个excel,让你去建表,但是表字段有几十个,如果复制粘贴加注释很浪费时间,我虽然技术不行,但是我抄起来比在座的各位强
我们再来看模板长什么样子,我把每一组都用不同的颜色区分了,注意:第四行才是表字段的开始,前三行都是表的描述
那么怎么从源数据到表字段的转换呢?
模板与将来的表结构对应关系如下图所示
接下来执行命令导入
命令如下
Option Explicit Dim mdl ' the current model Set mdl = ActiveModel If (mdl Is Nothing) Then MsgBox "There is no Active Model" End If Dim HaveExcel Dim RQ RQ = vbYes 'MsgBox("Is Excel Installed on your machine ?", vbYesNo + vbInformation, "Confirmation") If RQ = vbYes Then HaveExcel = True ' Open & Create Excel Document Dim x1 ' Dim wb Dim Sht Dim count Dim newTableName 'sheet中的表名 Dim singleTable 'powerdesigner中的表名 Dim existsFlag Set x1 = CreateObject("Excel.Application") '打开excel文件 Set wb = x1.Workbooks.Open("C:\Users\dell\Desktop\生成表模板.xlsx") '遍历每个sheet For Each Sht In wb.Sheets '打印sheet名 'msgbox( Sht.Name) 'msgbox( mdl.Tables.count) '获取到当前需要创建的表名,查看它是否在powerdesigner中已经存在 newTableName = Sht.Cells(1, 2).Value 'msgbox( newTableName) For Each singleTable In mdl.Tables 'msgbox(singleTable.Name) If singleTable.Name = newTableName Then existsFlag = True End If Next If existsFlag Then MsgBox (newTableName + "已经存在") '重置flag existsFlag = False Else '调用子模块 immigrate_function Sht, mdl count = count + 1 End If Next MsgBox "生成数据表结构共计" + CStr(count), vbOK + vbInformation, "表" '关闭流 Set Sht = Nothing wb.Close Set wb = Nothing x1.Quit Set x1 = Nothing Else HaveExcel = False End If '子程序模块 Sub immigrate_function(Sht, mdl) Dim rwIndex Dim tableName Dim colname Dim table Dim col 'on error Resume Next For rwIndex = 1 To 1000 Step 1 With Sht If .Cells(rwIndex, 1).Value = "" Then rwIndex = rwIndex + 1 If .Cells(rwIndex, 1).Value = "" Then Exit For End If End If If rwIndex = 1 Then Set table = mdl.Tables.CreateNew table.Name = .Cells(rwIndex, 2).Value ElseIf rwIndex = 2 Then table.Code = .Cells(rwIndex, 2).Value rwIndex = rwIndex + 1 Else colname = .Cells(rwIndex, 1).Value Set col = table.Columns.CreateNew col.Name = .Cells(rwIndex, 1).Value col.Code = .Cells(rwIndex, 2).Value col.Comment = .Cells(rwIndex, 4).Value col.DataType = .Cells(rwIndex, 3).Value End If End With Next End Sub
Set wb = x1.Workbooks.Open("C:\Users\dell\Desktop\生成表模板.xlsx"):这里换成自己的
参考了这位哥哥写的