一个基于VBA的数据字典生成宏(直接生成word文档)

发布一个可直接在word中,根据指定连接字段生成数据字典的宏,原文及代码:Generating Data Dictionary or Database Design Document using MS Word Macros ,实用于Sql Server 2005。2000下不行,2008没测试过……

用法:

1,新建一个word文档,在文档中新建一个宏,将代码copy到里面;

2,添加对Microsoft ActiveX Data Object的引用;

3,修改里面的连接字段Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;password=123;Initial Catalog=Northwind;Data Source=(local)

4,保存,并运行宏中的About方法

原代码中有几个不太完美的地方,由于之前接触过一点VBA,花了两个小时,动手改了一下:

1,汉化(其实就换了几个字符串而已:-D);

2,新增“描述”列,对应表中字段的说明(这个才是最有用的,想不通为啥“洋鬼子”不把此列显示出来);

3,将对表的描述,作为二级大纲标题显示出来;

4,在文档中生成TOC(如果一个项目中有上百张表,可以想象没有TOC的文档,可读性是多么差)。

代码直接贴在下面,希望有兴趣的朋友继续改进,别忘了发我一份就行:-)

Code‘AttributeVB_Name=”NewMacros”SubStart()’AttributeAbout.VB_Description=”Macrocreated3/18/2008byshashi”‘AttributeAbout.VB_ProcData.VB_Invoke_Func=”Normal.NewMacros.About””Macrocreated3/18/2008byshashi’DimconnAsNewADODB.ConnectionDimrsMainAsNewADODB.RecordsetDimrsFieldsAsNewADODB.RecordsetDimrsKeyAsNewADODB.RecordsetDimrsKeyTempAsADODB.RecordsetDimRangeAsRangeDimrowAsIntegerDimstrQueryAsStringDimstrFieldTypeAsStringDimIAsLong’OpenaconnectionobjectIfconn.State=1Thenconn.Closeconn.Open”Provider=SQLOLEDB.1;PersistSecurityInfo=False;UserID=sa;password=123456;InitialCatalog=PQMAGIC;DataSource=(local)”‘OpentherecordsettoretrievethetablesinthedatabaseIfrsMain.State=1ThenrsMain.ClosersMain.Open”Selecttb.[name],ex.valuefromsys.tablesastbinnerjoinsys.extended_propertiesasex”&_”ontb.[object_id]=ex.major_idwheretb.[name]<>’sysdiagrams’andex.minor_id=0orderbyname”,conn,adOpenKeyset,adLockOptimisticrow=1’IteratethroughthetablesrecordsetWhileNotrsMain.EOF’StartwiththeactivedocumentWithWord.ActiveDocument’ProceduretosetthetablenameCallSetTableName(rsMain(0),rsMain(1))’QuerytogettheIndexes,Views,StoredProcedures,Functions,TriggersofthetablestrQuery=”selectind.name,’INDEX’ascol2fromsys.indexesindinnerjoinsys.tablestab”&_”onind.object_id=tab.object_idwheretab.name='”&rsMain(0)&”‘”&_”andind.nameisnotnull”&_”union”&_”SelectDistinctProcedures.Name,’View’ascol2FromSysObjects”&_”Join(SysObjectsProceduresJoinSysDependsonProcedures.Id=SysDepends.Id)”&_”OnSysDepends.DepId=SysObjects.IdWhereSysObjects.XType=’U'”&_”AndProcedures.XType=’V’AndSysObjects.Name='”&rsMain(0)&”‘”&_”union”&_”SelectDistinctProcedures.Name,’StoredProcedure’ascol2FromSysObjects”&_”Join(SysObjectsProceduresJoinSysDependsonProcedures.Id=SysDepends.Id)”&_”OnSysDepends.DepId=SysObjects.IdWhereSysObjects.XType=’U'”&_”AndProcedures.XType=’P’AndSysObjects.Name='”&rsMain(0)&”‘”&_”AND(lower(Procedures.Name)like’spalias%’orlower(Procedures.Name)like’spcustom%'”&_”orlower(Procedures.Name)like’spncustom%’)”&_”union”&_”SelectDistinctProcedures.Name,’Function’ascol2FromSysObjects”&_”Join(SysObjectsProceduresJoinSysDependsonProcedures.Id=SysDepends.Id)”&_”OnSysDepends.DepId=SysObjects.IdWhereSysObjects.XType=’U'”&_”AndProcedures.XTypein(‘Fn’,’If’,’Tf’)AndSysObjects.Name='”&rsMain(0)&”‘”&_”union”&_”SelectDistinctProcedures.Name,’Trigger’ascol2FromSysObjects”&_”Join(SysObjectsProceduresJoinSysDependsonProcedures.Id=SysDepends.Id)”&_”OnSysDepends.DepId=SysObjects.IdWhereSysObjects.XType=’U'”&_”AndProcedures.XType=’Tr’AndSysObjects.Name='”&rsMain(0)&”‘”‘CreatearecordsettofindIndexes,Views,StoredProcedures,Functions,TriggersofthetableIfrsKey.State=1ThenrsKey.ClosersKey.OpenstrQuery,conn,adOpenKeyset,adLockReadOnly’***************Index************************IfNotrsKeyIsNothingThen’ClonetherecordsetobjecttofindtheindexesofthetableSetrsKeyTemp=rsKey.Clone(adLockReadOnly)rsKeyTemp.Filter=”col2=’INDEX'”‘SetthelabellinginthedocumentCallSetHeading(“索引:”)IfrsKeyTemp.EOFThenCallSetTextAfter(“-无-“)EndIfWhileNotrsKeyTemp.EOFCallSetTextAfter(rsKeyTemp(0))rsKeyTemp.MoveNextWend’****************************************************’******************Views***************’ClonetherecordsetobjecttofindtheindexesofthetableSetrsKeyTemp=rsKey.Clone(adLockReadOnly)rsKeyTemp.Filter=”col2=’View'”‘SetthelabellinginthedocumentCallSetHeading(“视图:”)IfrsKeyTemp.EOFThenCallSetTextAfter(“-无-“)EndIfWhileNotrsKeyTemp.EOFCallSetTextAfter(rsKeyTemp(0))rsKeyTemp.MoveNextWend’************************************’******************StoredProcedures***************’ClonetherecordsetobjecttofindtheindexesofthetableSetrsKeyTemp=rsKey.Clone(adLockReadOnly)rsKeyTemp.Filter=”col2=’StoredProcedure'”‘SetthelabellinginthedocumentCallSetHeading(“存储过程:”)IfrsKeyTemp.EOFThenCallSetTextAfter(“-无-“)EndIfWhileNotrsKeyTemp.EOFCallSetTextAfter(rsKeyTemp(0))rsKeyTemp.MoveNextWend’************************************’******************Functions***************’ClonetherecordsetobjecttofindtheindexesofthetableSetrsKeyTemp=rsKey.Clone(adLockReadOnly)rsKeyTemp.Filter=”col2=’Function'”‘SetthelabellinginthedocumentCallSetHeading(“用户自定义函数:”)IfrsKeyTemp.EOFThenCallSetTextAfter(“-无-“)EndIfWhileNotrsKeyTemp.EOFCallSetTextAfter(rsKeyTemp(0))rsKeyTemp.MoveNextWend’************************************’******************Triggers***************’ClonetherecordsetobjecttofindtheindexesofthetableSetrsKeyTemp=rsKey.Clone(adLockReadOnly)rsKeyTemp.Filter=”col2=’Trigger'”‘SetthelabellinginthedocumentCallSetHeading(“触发器:”)IfrsKeyTemp.EOFThenCallSetTextAfter(“-无-“)EndIfWhileNotrsKeyTemp.EOFCallSetTextAfter(rsKeyTemp(0))rsKeyTemp.MoveNextWendEndIf’************************************’SetthelabellinginthedocumentCallSetHeading(“表详细信息”)’ProceduretopositionthecursorinthedocumentCallMoveDownOnErrorGoToErr’QuerytogetthecolumnnamesofthetablestrQuery=””strQuery=”selectst.name,col.*,ex.valuefromsyscolumnscolinnerjoin”&_”sysobjectssoboncol.id=sob.idandsob.XType=’U'”&_”innerjoinsystypesstoncol.usertype=st.usertype”&_”andcol.xtype=st.xtype”&_”andsob.Name='”&rsMain(0)&”‘”&_”innerjoinsys.extended_propertiesexoncolid=ex.minor_idandcol.id=ex.major_id”IfrsFields.State=1ThenrsFields.ClosersFields.OpenstrQuery,conn,adOpenKeyset,adLockOptimisticIfNotrsFieldsIsNothingAndrsFields.Fields.Count>0Then’Createthetableinthedocumenttodisplaythecolumns’Tablewilldisplay”FieldName”,”FieldType”,”Size”,”Key”,”Description”.Tables.AddRange:=Selection.Range,NumRows:=rsFields.RecordCount+1,NumColumns_:=6,DefaultTableBehavior:=wdWord9TableBehavior,AutoFitBehavior:=_wdAutoFitFixed.Tables(row).Cell(1,1).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,1).Range.InsertBefore”字段名”.Tables(row).Cell(1,1).Range.Bold=True.Tables(row).Cell(1,2).Range.InsertBefore”类型”.Tables(row).Cell(1,2).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,2).Range.Bold=True.Tables(row).Cell(1,3).Range.InsertBefore”长度”.Tables(row).Cell(1,3).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,3).Range.Bold=TrueCall.Tables(row).Columns(2).SetWidth(50,wdAdjustSameWidth)Call.Tables(row).Columns(3).SetWidth(40,wdAdjustSameWidth)Call.Tables(row).Columns(4).SetWidth(40,wdAdjustSameWidth)Call.Tables(row).Columns(5).SetWidth(100,wdAdjustSameWidth)Call.Tables(row).Columns(6).SetWidth(80,wdAdjustSameWidth).Tables(row).Cell(1,4).Range.InsertBefore”键”.Tables(row).Cell(1,4).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,4).Range.Bold=True.Tables(row).Cell(1,5).Range.InsertBefore”描述”.Tables(row).Cell(1,5).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,5).Range.Bold=True.Tables(row).Cell(1,6).Range.InsertBefore”备注”.Tables(row).Cell(1,6).Shading.BackgroundPatternColor=wdColorGray20.Tables(row).Cell(1,6).Range.Bold=TrueI=0WhileNotrsFields.EOF.Tables(row).Cell(I+2,1).Range.InsertBeforersFields(1).Tables(row).Cell(I+2,2).Range.InsertBeforersFields(0).Tables(row).Cell(I+2,3).Range.InsertBeforersFields(6)Dimarr()AsStringarr=Split(rsFields(33),””)IfUBound(arr)=3Then.Tables(row).Cell(I+2,5).Range.InsertBefore”关联”&arr(2)&”表”Else.Tables(row).Cell(I+2,5).Range.InsertBeforersFields(33)EndIfrsFields.MoveNextI=I+1WendEndIf’Querytoretrievetheconstraints,KeysandIdentityofthetablestrQuery=”selectc.COLUMN_NAME,CONSTRAINT_TYPE,”asDefaultValue”&_”fromINFORMATION_SCHEMA.TABLE_CONSTRAINTSpk,”&_”INFORMATION_SCHEMA.KEY_COLUMN_USAGEc”&_”wherepk.TABLE_NAME='”&rsMain(0)&”‘”&_”andc.TABLE_NAME=pk.TABLE_NAME”&_”andc.CONSTRAINT_NAME=pk.CONSTRAINT_NAME”&_”union”&_”selectc.name,’DEFAULTCONSTRAINT’ASdefaultcontraint,”&_”replace(replace(ind.definition,'(‘,”),’)’,”)ASDefaultValue”&_”fromsys.default_constraintsind”&_”innerjoinsys.tablestab”&_”onind.parent_object_id=tab.object_id”&_”innerjoinsys.columnsc”&_”ontab.object_id=c.object_idand”&_”c.column_id=ind.parent_column_id”&_”wheretab.name='”&rsMain(0)&”‘”&_”union”&_”selectCOLUMN_NAME,’IDENTITY’ASdefaultcontraint,”asDefaultValue”&_”fromINFORMATION_SCHEMA.Columns”&_”whereTABLE_NAME='”&rsMain(0)&”‘”&_”andCOLUMNPROPERTY(object_id(TABLE_NAME),COLUMN_NAME,’IsIdentity’)=1″IfrsKey.State=1ThenrsKey.ClosersKey.OpenstrQuery,conn,adOpenKeyset,adLockOptimisticIfNotrsKeyIsNothingThen’Iteratethroughtherecordsettofindtheconstraints,KeysandIdentityofthetableWhileNotrsKey.EOFI=0rsFields.MoveFirst’Iteratethroughtthefieldsrecordsetandsetthekeysinthe4and5columnsofthetableDoWhileNotrsFields.EOFIfUCase(rsFields(1))=UCase(rsKey(0))ThenIfUCase(rsKey(1))=”FOREIGNKEY”Then.Tables(row).Cell(I+2,4).Range.InsertBefore”外键”ExitDoElseIfUCase(rsKey(1))=”PRIMARYKEY”Then.Tables(row).Cell(I+2,4).Range.InsertBefore”主键”ExitDoElseIfUCase(rsKey(1))=”DEFAULTCONSTRAINT”Then.Tables(row).Cell(I+2,6).Range.InsertBefore”默认”&rsKey(2)ExitDoElseIfUCase(rsKey(1))=”IDENTITY”Then.Tables(row).Cell(I+2,6).Range.InsertBefore”标识列”ExitDoEndIfEndIfI=I+1rsFields.MoveNextLooprsKey.MoveNextWendEndIfEndWithrow=row+1rsMain.MoveNextWendSelection.HomeKeyunit:=wdStoryCallInsertDomainSelection.TypeParagraphSelection.TypeParagraphExitSubErr:MsgBoxErr.DescriptionCallSetHeading(“Errorinthetable:”&rsMain(0))SetrsMain=NothingSetrsFields=NothingSetrsKey=NothingEndSubSubMoveDown()DimRange3AsRangeDimIAsIntegerOnErrorResumeNextI=ActiveDocument.Tables.CountSetRange3=ActiveDocument.Range(Start:=ActiveDocument.Range.End,End:=ActiveDocument.Range.End)Range3.MoveEndunit:=wdCharacter,Count:=1Range3.SetRangeStart:=Range3.Start+2,End:=Range3.EndRange3.SelectWithSelection.CollapseDirection:=wdCollapseEnd.TypeParagraphEndWithEndSubSubSetText(strAsString)DimRange3AsRangeDimIAsIntegerOnErrorResumeNextI=ActiveDocument.Tables.CountSetRange3=ActiveDocument.Range(Start:=ActiveDocument.Tables(I).Range.End,End:=ActiveDocument.Tables(I).Range.End)Range3.MoveEndunit:=wdCharacter,Count:=1Range3.SetRangeStart:=Range3.Start+2,End:=Range3.End+Len(str)Range3.SelectWithSelection.CollapseDirection:=wdCollapseEnd.TypeParagraph.InsertParagraph.Font.Name=”verdana”.Font.Size=10.InsertBeforestrEndWithEndSubSubSetTextAfter(strAsString)DimRange3AsRangeDimIAsIntegerOnErrorResumeNextI=ActiveDocument.Tables.CountSetRange3=ActiveDocument.Range(Start:=ActiveDocument.Range.End,End:=ActiveDocument.Range.End)Range3.MoveEndunit:=wdCharacter,Count:=1Range3.SetRangeStart:=Range3.Start+2,End:=Range3.End+Len(str)Range3.SelectWithSelection.CollapseDirection:=wdCollapseEnd.TypeParagraph.Font.Name=”verdana”.Font.Size=10.InsertAftervbTab&strEndWithEndSubSubSetHeading(strAsString)DimRange3AsRangeDimIAsIntegerOnErrorResumeNextI=ActiveDocument.Tables.CountSetRange3=ActiveDocument.Range(Start:=ActiveDocument.Range.End,End:=ActiveDocument.Range.End)Range3.MoveEndunit:=wdCharacter,Count:=1Range3.SetRangeStart:=Range3.Start+2,End:=Range3.End+Len(str)Range3.SelectWithSelection.CollapseDirection:=wdCollapseEnd.TypeParagraph.Font.Name=”verdana”.Font.Size=10.TypeParagraph.Font.Bold=wdToggle.Font.ColorIndex=wdGreen.TypeText(Space(3)&str).Font.ColorIndex=wdBlack.Font.Bold=wdToggleEndWithEndSubSubSetTableName(strTableAsString,strDescriptionAsString)DimRange3AsRangeDimIAsIntegerOnErrorResumeNextI=ActiveDocument.Tables.CountSetRange3=ActiveDocument.Range(Start:=ActiveDocument.Tables(I).Range.End,End:=ActiveDocument.Tables(I).Range.End)Range3.MoveEndunit:=wdCharacter,Count:=1Range3.SetRangeStart:=Range3.Start+2,End:=Range3.End+Len(strTable)Range3.SelectWithSelection.CollapseDirection:=wdCollapseEnd.TypeParagraph.Font.Name=”verdana”.Font.Size=11.Font.Italic=True.Font.Bold=wdToggle.Font.Color=wdColorDarkRed.TypeTextstrDescription+”:”.Font.ColorIndex=wdBlack.Font.Bold=wdToggle.TypeTextstrTable.Font.Italic=False.Paragraphs.OutlineLevel=wdOutlineLevel2.TypeParagraph.Paragraphs.OutlineLevel=wdOutlineLevelBodyTextEndWithEndSubSubInsertDomain()”DomainMacro’宏在2009-05-08由MicrosoftUSER录制’WithActiveDocument.TablesOfContents.AddRange:=Selection.Range,RightAlignPageNumbers:=_True,UseHeadingStyles:=True,UpperHeadingLevel:=1,_LowerHeadingLevel:=3,IncludePageNumbers:=True,AddedStyles:=””,_UseHyperlinks:=True,HidePageNumbersInWeb:=True,UseOutlineLevels:=_True.TablesOfContents(1).TabLeader=wdTabLeaderDots.TablesOfContents.Format=wdIndexIndentEndWithEndSub有时,明知错了,却欲罢不能,

一个基于VBA的数据字典生成宏(直接生成word文档)

相关文章:

你感兴趣的文章:

标签云: