我在word doc中有一个表,我想用VBA来选择特定的单元格。我制作的每个文档都遵循一个具有4xZ表的模板,这意味着我有4列和不同的行数,具体取决于文档。
我想要做的是选择表格的第3列,除了第1行,因为那是标题,迭代每个单元格,抓取值并通过switch语句运行它,这样我就可以改变单元格的颜色了值。
我找到了这段代码here:
Sub SelectColumn()
'Updateby20140510
Dim xColIndex As Integer
Dim xRowIndex As Integer
xIndex = Application.ActiveCell.Column
xRowIndex = Application.ActiveSheet.Cells(Rows.Count, xIndex).End(xlUp).Row
Range(Cells(2, xIndex), Cells(xRowIndex, xIndex)).Select
End Sub
我想我可以修改代码来说:
xIndex = Application.ActiveCell.Columns(3)
但是,如果它工作并选择第3列和除第1列之外的第3列中的所有行,我不明白如何继续并开始迭代。我知道迭代代码是这样的:
For Each oRow In oTbl.Rows
...
Next
但我不知道如何引用第3列的选择,在for循环中向下排2行。有任何想法吗?
编辑1:我意识到上面的代码是excel。因此,经过数小时的挖掘并无济于事,我决定采用快速而肮脏的方法。这是代码:
For Each oClm In ActiveDocument.Tables(1).Columns
If clmNum = 3 Then
' Loop through each cell in the current row.
For Each oCell In oClm.Cells
If rowNum = 2 Then
' Set sCellText equal to text of the cell.
' Note: This section can be modified to suit
' your programming purposes.
oCellText = oCell.Range
oCellText = Left(oCellText, Len(oCellText) - 1)
oCellText = CStr(oCellText)
Select Case oCellText
Case "Complete"
oCell.Interior.ColorIndex = wdGreen
Case "Partial"
oCell.Interior.ColorIndex = wdYellow
Case "Incomplete"
oCell.Interior.ColorIndex = wdRed
End Select
End If
rowNum = rowNum + 1
Next oCell
End If
clmNum = clmNum + 1
Next oClm
现在唯一的问题是,我在switch语句之前断点并且oCellText
中的值是“Complete”但它跳过switch语句中的值。我不知道为什么,它应该进入声明,但它的行为就像它不一样。这就是为什么我有cstr
线,我想它没有做任何事情,但没有伤害尝试。
为什么案例陈述失败的任何想法?
编辑2:我发现案件失败的原因。因为oCellText
之后有了新的一条线。我用这段代码删除了它:
oCellText = Replace(oCellText, Chr(13), "")
但案例陈述仍然不匹配。有任何想法吗?
编辑3:我现在一切都工作了。但我只是不高兴我必须通过嵌套for循环遍历单元格,希望有一种更简单的方法。
更容易的方法,如果你仍然在寻找你可以直接解决细胞
for y = 2 to activedocument.tables(1).rows.count
activedocument.tables(1).cell(3,y).select
' do your stuff here
next y