我有一个word文档,我想填写来自excel的相同单词。可以说两者都位于c:\ test中
我对使用vba有一些了解,但这个有点过了。
在我的word文档中,我有句话可以说:
我是firstname
lastname
,我的用户名是username
,这是我的部门:department
我有一个名为data的excel,带有一个名为sheet1的表,其中包含一个名为users的表和一些列:username,firstname,lastname,department。该表是一个odbc连接表,它会在工作簿打开时刷新。
username
,并根据该值填写其他框。以下代码:
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
答案 0 :(得分:2)
以下代码应该可以满足您的需求。请注意以下事项:
UpdateBookmark
程序才能使其正常工作。代码:
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