View Full Version : Comparing Cell Values in Word Tables
I am trying to write a macro that compares the values in two cells within one of several tables in a document, but not having much success figuring out how to use vba to return the value of the cell contents. Can anyone offer some pointers?
Thanks.
fumei
04-14-2006, 02:53 AM
Hmmm, I am tempted to say.."Look up Cell in Help", but it does geta little tricky. There are actually a number of routes you could take. That is the ...ahem...beauty, of VBA.
First off, you can get the contents of the cell by the text of its Range. If you are going to mess around in Word with VBA, you MUST get a grasp on the Selection object, and the Range object.
You also need to lay out your plans step-by-step. Do you know WHICH cells you want to get values from? Do you need to be able to input whatever ones you want? Are you only ever going to calculate between two cells...never three...or four? There are a bunch more serious questions, but here is ONE idea to help move you along.
Sub DoSomethingTwoCells()
Dim Cell_A As String
Dim Cell_B As String
' get the string value of a given cell - the 2nd column
' 3rd row cell, in the third table in the document.
Cell_A = ActiveDocument.Tables(3).Cell(3, 2).Range.Text
' get another one - Row 1, Col 3, of the third table
Cell_B = ActiveDocument.Tables(3).Cell(1, 3).Range.Text
' as these are string values, they contain the End-Of-Cell
' marker (a kind of jazzed up paragraph mark). These
' must be removed otherwise you get a Type mismatch error
Cell_A = Left(Cell_A, Len(Cell_A) - 1)
Cell_B = Left(Cell_B, Len(Cell_B) - 1)
Msgbox Cell_A * Cell_B ' multiplies the cells
' this could have not used the reassigning of the variables
' and displayed the result directly
MsgBox Left(Cell_A, Len(Cell_A) - 1) * Left(Cell_B, Len(Cell_B) - 1)
End Sub
There are so many possibilities, that it is crucial that you properly define what you want to do.
mdmackillop
04-14-2006, 03:19 AM
Hi JCW,
Welcome to VBAX.
Here's some sample code to compare a selected cell with other table and return data/location. If you can post a sample. I'm sure we can assist further.
Regards
MD
Option Explicit
Sub Tables()
Dim MyVal, i As Long, c, t
'Get value of current cell
MyVal = Selection.Cells(1)
'Check each table for same value
For Each t In ActiveDocument.Tables
i = i + 1
For Each c In t.Range.Cells
If c = MyVal Then
MsgBox Left(c, Len(c) - 1) & " - " & "Table " & i & _
" : Row " & c.RowIndex & " : Column " & c.ColumnIndex
End If
Next
Next
End Sub
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.