Click here to Skip to main content
15,664,272 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
new to VBA and need help..Thanks
I have two word tables, one table contains part number and id,
and the other one contains id and other information,
how could use the id in table 2 to search the part number from table 1
and save the part number to table 2
at the end, I need to export the table as text file
Is this possible in VBA? Thanks..
Maciej Los 17-Sep-12 16:09pm    
More details, please... Example data...

1 solution

Yes, it's possible in VBA, but we need more details to help you!

Example code would looks like:
Option Explicit

Sub MergeTables()
Dim srcDoc As Document, dstDoc As Document
Dim srcTbl1 As Table, srcTbl2 As Table, dstTbl As Table
Dim rng As Range, sTmp As String
Dim r As Long, rc As Long

'on error got error handler
On Error GoTo Err_MergeTables

'this document
Set srcDoc = ThisDocument
'table 1
Set srcTbl1 = srcDoc.Tables(1)
'table 2
Set srcTbl2 = srcDoc.Tables(2)

'add new document
Set dstDoc = Documents.Add
'add table in to new document
Set dstTbl = dstDoc.Tables.Add(dstDoc.Range, srcTbl1.Rows.Count, srcTbl1.Columns.Count)

'get row count
rc = srcTbl1.Rows.Count
'go through the collection of rows
'start from 2. row, ignore header ;)
For r = 2 To rc
    'get ID from column 1
    Set rng = srcTbl1.Cell(r, 1).Range
    dstTbl.Cell(r, 1).Range.Text = rng.Text
    'find ID in the 2. table and get some information
    sTmp = FindIDAndGetInfo(rng.Text)
    'insert info...
    dstTbl.Cell(r, 2).Range.Text = sTmp

    On Error Resume Next
    'clean up ;)
    Set rng = Nothing
    Set dstTbl = Nothing
    Set srcTbl2 = Nothing
    Set srcTbl1 = Nothing
    Exit Sub

    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_MergeTables

End Sub

Function FindIDAndGetInfo(sID As String) As String
Dim sRetVal As String

'you need to implement the body of function
'tip: go through the collection of cells ;)

FindIDAndGetInfo = sRetVal
End Function
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900