使用 Microsoft.Office.Interop.Word 查找所选单元格的索引

Finding the index of a selected cell using Microsoft.Office.Interop.Word

注意:我已经使用暴力双 for 循环解决了这个问题。我需要一种更快、更有效的方法来专门在 C# 中解决它。

考虑下面的单词 table。

我需要一种有效的方法来找到给定的列和给定的行,并将文本放置在相交的单元格中。例如,假设我的列为 1,行为 A。然后文本将进入索引为 row:2,col:2.

的单元格

我尝试过的事情: 遍历所有行和列。这很慢并且需要大量时间。 为了加快速度,我尝试使用 Range.Find,但很难知道找到的单元格在 table 的上下文中的位置。这是我在想什么的一些粗略代码。我很清楚这缺少检查是否找到项目或是否有多个项目但我可以稍后处理。

int col;
int row;

var searchRange = table.Range;
var isFound = searchRange.Find.Execute(FindText:rowText);
if(isFound){
 searchRange.Select();
col = searchRange.SOME_FUNCTION_THAT_WILL_REVEAL_THE_CELLS_COL_INDEX_WITHIN_THE_TABLE();
}

var searchRange = table.Range;
var isFound = searchRange.Find.Execute(FindText:rowText);
if(isFound){
 searchRange.Select();
row = searchRange.SOME_FUNCTION_THAT_WILL_REVEAL_THE_CELLS_ROW_INDEX_WITHIN_THE_TABLE();
}

table.Cell(row, col).Text = "Some text For Desired Location";

这正是您想要的。将其粘贴到 VBA 模块中,首先 select 在 table 之外,然后通过代码按 F8。接下来使鼠标光标 select 成为 table 中的一个单元格,然后 F8 通过此代码:

Sub SelectionInfo()
     '
    Dim iSelectionRowEnd As Integer
    Dim iSelectionRowStart As Integer
    Dim iSelectionColumnEnd As Integer
    Dim iSelectionColumnStart As Integer
    Dim lngStart As Long
    Dim lngEnd As Long
     
     ' Check if Selection IS in a table
     ' if not, exit Sub after message
    If Selection.Information(wdWithInTable) = False Then
        MsgBox "Selection is not in a table.  Exiting macro."
    Else
        lngStart = Selection.Range.Start
        lngEnd = Selection.Range.End
         
         ' get the numbers for the END of the selection range
        iSelectionRowEnd = Selection.Information(wdEndOfRangeRowNumber)
        iSelectionColumnEnd = Selection.Information(wdEndOfRangeColumnNumber)
         
         ' collapse the selection range
        Selection.Collapse Direction:=wdCollapseStart
         
         ' get the numbers for the END of the selection range
         ' now of course the START of the previous selection
        iSelectionRowStart = Selection.Information(wdEndOfRangeRowNumber)
        iSelectionColumnStart = Selection.Information(wdEndOfRangeColumnNumber)
         
         ' RESELECT the same range
        Selection.MoveEnd Unit:=wdCharacter, Count:=lngEnd - lngStart
         
         ' display the range of cells covered by the selection
        MsgBox "The selection covers " & Selection.Cells.Count & " cells, from Cell(" & _
        iSelectionRowStart & "," & iSelectionColumnStart & ") to Cell(" & _
        iSelectionRowEnd & "," & iSelectionColumnEnd & ")."
    End If
End Sub

REF:http://www.vbaexpress.com/kb/getarticle.php?kb_id=867