将sql查询行导入单独的单词表

时间:2013-11-11 20:35:47

标签: ms-word word-vba

我需要创建一个基于sql server表的警报字典,其中定义了警报。

sql警报表包含以下内容的列:警报名称,类型,严重性,代码,附加数据,用户操作等。目前有数百个警报。

我需要为每个警报添加一个单词表,将查询中的值插入到sql表中。

有关如何执行此操作的任何建议将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

我自己想出来了。首先从查询创建Excel电子表格并从那里开始工作似乎最容易,这就是我所做的。接下来,我创建了以下VBA宏:

Sub BuildAlarmDict()

Dim exApp As New Excel.Application
Dim exWb As Excel.Workbook
Dim exWs As Excel.Worksheet

Dim row As Integer
Dim tbl As Word.Table
Dim para As Paragraph
Dim myRng As Range

Set exWb = exApp.Workbooks.Open("C:\AlarmDictData.xls")
Set exWs = exWb.Sheets(1)

For row = exWs.UsedRange.Rows.Count To 1 Step -1

    Set myRng = ActiveDocument.Range(Start:=Selection.Range.End, End:=Selection.Range.End)

    With myRng
        .Collapse Direction:=wdCollapseEnd
        .InsertParagraphAfter
        .Collapse Direction:=wdCollapseEnd
    End With

    Set tbl = ActiveDocument.Tables.Add(Range:=myRng, NumRows:=6, NumColumns:=2)

    With tbl

        .AllowPageBreaks = False
        .Columns(1).Width = 122
        .Columns(2).Width = 351

        With .Rows(1)
            .Cells.Merge
            .Shading.BackgroundPatternColorIndex = 16

            With .Range
                .Bold = True
                .ParagraphFormat.Alignment = wdAlignParagraphCenter
                .Font.Size = 12
            End With
        End With

        With .Borders
            .InsideLineStyle = wdLineStyleSingle
            .OutsideLineStyle = wdLineStyleSingle
        End With

        .Cell(1, 1).Range.Text = exWs.Cells(row, 1) & " : " & exWs.Cells(row, 2)
        .Cell(2, 1).Range.Text = "Alarm Code"
        .Cell(2, 2).Range.Text = exWs.Cells(row, 1)
        .Cell(3, 1).Range.Text = "Specific Problem"
        .Cell(3, 2).Range.Text = exWs.Cells(row, 2)
        .Cell(4, 1).Range.Text = "Perceived Severity"
        .Cell(4, 2).Range.Text = exWs.Cells(row, 3)
        .Cell(5, 1).Range.Text = "Probable Cause"
        .Cell(5, 2).Range.Text = exWs.Cells(row, 4)
        .Cell(6, 1).Range.Text = "Additional Text"
        .Cell(6, 2).Range.Text = exWs.Cells(row, 5)
    End With
Next

exWb.Close
Set exApp = Nothing

End Sub