简体   繁体   English

使用VBA在Word文档中填充Excel数据

[英]Populate excel data in word document with VBA

I have a word document and I would like to populate same words coming from excel. 我有一个Word文档,我想填充来自excel的相同单词。 Lets say both are located in c:\\test I have some knowledge to using vba but this one is a bit over it. 可以说它们都位于c:\\ test中,我对使用vba有一定的了解,但是这个有点过头了。 In my word document I have a sentence lets say: I am firstname lastname and my username is username and this is my department: department 在我的Word文档我有一句话可以说:我firstname lastname和我的用户名是username ,这是我的部门: department

I have an excel called data, with a sheet called sheet1 with a table called users and some column: username, firstname, lastname, department. 我有一个称为data的excel,有一个名为sheet1的工作表,其中包含一个名为users的表和一些列:用户名,名字,姓氏,部门。 The table is an odbc connected table and it refreshes when the workbook opens. 该表是一个odbc连接表,在工作簿打开时将刷新。

  1. My first question is what kind of object should I use for firstname, lastname, username, deparment in word? 我的第一个问题是我应该使用哪种对象的名字,姓氏,用户名和语言修饰? I inserted a Rich text control content and inside that a legacy form/textform field and renamed the bookmarks to firstname, lastname.. etc. 我插入了富文本控件内容,并在其中保留了一个旧式表单/文本表单字段,并将书签重命名为名字,姓氏等。
  2. I would like to populate the data in word from excel using macro and vlookup. 我想使用宏和vlookup从excel中用字填充数据。 I don't really have idea how this can be done, I have a bit of code, but it does not work. 我真的不知道该如何完成,我有一些代码,但是它不起作用。 When the macro started a window should pop up asking the username and based on that value the other boxes will be filled in. 宏启动后,会弹出一个窗口询问username并根据该值填写其他框。

Code Below: 下面的代码:

Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Dim username As String
Dim firstname As String
Dim lastname As String
Dim department As String

username = InputBox("Please enter the username", "Input")

Set exWb = objExcel.Workbooks.Open("C:\test\data.xlsx")

username = objExcel.WorksheetFunction.VLookup(username, _
 eexWb.ActiveSheet.Range("A:F"), 1, False)

firstname = objExcel.WorksheetFunction.VLookup(username, _
 eexWb.ActiveSheet.Range("A:F"), 2, False)

lastname = objExcel.WorksheetFunction.VLookup(username, _
 eexWb.ActiveSheet.Range("A:F"), 3, False)

department = objExcel.WorksheetFunction.VLookup(username, _
 eexWb.ActiveSheet.Range("A:F"), 4, False)

exWb.Close

Set exWb = Nothing

The below code should accomplish what you need. 下面的代码应该可以满足您的需求。 Take the following notes: 请注意以下几点:

  1. I used early binding (to take advantage of intellisense). 我使用了早期绑定(以利用智能感知)。 In the Word VBE, in Tools > References, check Microsoft Excel XX.X Object Library 在Word VBE中的“工具”>“引用”中,检查Microsoft Excel XX.X对象库
  2. You can create a simple bookmark with no need to insert objects. 您可以创建简单的书签,而无需插入对象。 You may still wish to do that, but you may need to adjust the UpdateBookmark procedure to get it to work properly. 您可能仍然希望这样做,但是您可能需要调整UpdateBookmark过程以使其正常工作。

Code: 码:

Sub LoadInfo()

    Dim objExcel As Excel.Application 'note early binding (set in Tools > References > Microsoft Excel XX.X library
    Set objExcel = New Excel.Application

    Dim username As String
    Dim firstname As String
    Dim lastname As String
    Dim department As String

    username = InputBox("Please enter the username", "Input")

    Dim exWB as Excel.Workbook        
    Set exWB = objExcel.Workbooks.Open("C:\test\data.xlsx")

    With exWB.Worksheets("Sheet1")

        Dim rngUN As Excel.Range
        Set rngUN = .Columns("A").Find(what:=username, lookat:=xlWhole)

        If Not rngUN Is Nothing Then

            firstname = rngUN.Offset(, 2)
            lastname = rngUN.Offset(, 3)
            department = rngUN.Offset(, 4)

        Else

            MsgBox "Username Not Found. Exiting Sub"
            GoTo ExitSub

        End If

    End With

    UpdateBookmark "username", username, ActiveDocument, False
    UpdateBookmark "firstname", firstname, ActiveDocument, False
    UpdateBookmark "lastname", lastname, ActiveDocument, False
    UpdateBookmark "department", department, ActiveDocument, False

ExitSub:
        exWB.Close
        objExcel.Quit


    End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextToUse As String, wDoc As Word.Document, Optional bReplace As Boolean)
'updates a bookmark range in Word without removing the bookmark name

    Dim BMRange As Word.Range
    Dim sTest As String

    With wDoc

        Set BMRange = .Bookmarks(BookmarkToUpdate).Range

        'if text already exists, add new to old with a carriange return in between
        sTest = BMRange.Text

        If sTest = "" Or bReplace Then

            BMRange.Text = TextToUse

        Else

            BMRange.Text = sTest & vbCr & TextToUse

        End If

        .Bookmarks.Add BookmarkToUpdate, BMRange

    End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM