2016-10-04 56 views
1

我的VBA根據標準動態地寫入幾個表並且工作得很好。在Word中的文本之後訪問VBA-插入複選框表

例如,這裏是添加一行,格式化並前進到下一行。

 oDoc.Tables(t).Rows.Add 'add a row below control number 
     oDoc.Tables(t).Rows(i).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter 
     oDoc.Tables(t).Rows(i).Shading.BackgroundPatternColor = oTableHeaderColor 
     i = i + 1 'advance to row below control number row. 
     oDoc.Tables(t).Cell(i, 2).Range.Text = "Check Definition" 

我做這種方式,因爲我只是不知道任何給定的表有多少行是 - 所以我創建的行,我需要他們,可能是笨拙,但它的工作原理。

我需要做的是添加一個可檢查的複選框到這樣的文本行。

計劃:☐

我嘗試了幾種方法,只是似乎沒有工作。據我可以告訴它是因爲我不創建表然後選擇它。我試過錄制一個宏,並且首先顯示了關於選擇的一點。

這是我得到的,它彈出一個錯誤。

oDoc.Tables(t).Cell(i, 2).Range.Text = "Planned: " & oDoc.Tables(t).Cell(i, 1).Range.ContentControls.Add(wdContentControlCheckBox) 

我得到「要求集合的成員不存在。

如果我試圖把它放在兩行它只是簡單地覆蓋電池1.與複選框,我似乎無法到它的位置在小區第一結束。任何想法?我試過的insertBefore和作品,但我在同一單元格中插入數個複選框。

任何想法? 謝謝。

回答

1

獲取文本+複選框+其他文本+第二個複選框一個細胞很棘手。

這可能是少數情況下,你實際上必須使用Selection對象。

這個工作對我來說在Word中:

Dim oDoc As Word.Document 
Set oDoc = ThisDocument 
Const t = 1 
Const i = 1 

Dim rng As Word.Range 
Dim iCheck As Long 
Dim sLabel As String 

Set rng = oDoc.Tables(t).Cell(i, 2).Range 
rng.Select 
With Selection 
    .Collapse Direction:=wdCollapseStart 
    For iCheck = 1 To 3 
     sLabel = Choose(iCheck, "Planned: ", " Done: ", " Perhaps: ") 

     .TypeText Text:=sLabel 
     .Range.ContentControls.Add wdContentControlCheckBox 
     ' move cursor after checkbox 
     .MoveRight Unit:=wdCharacter, Count:=2 
    Next iCheck 
End With 

在Access,使用oWord.Selection代替(或者你有作爲參考字什麼的)。

以下工作適用於單個複選框,但我沒有設法在之後創建第二個附加文本。

Dim rng As Word.Range 
Set rng = oDoc.Tables(t).Cell(i, 2).Range 
rng.Text = "Planned: " 
' set range to end of cell 
rng.Collapse Direction:=wdCollapseEnd 
' I'm not entirely sure why this is needed, but without the checkbox goes into the next cell 
rng.MoveEnd Unit:=wdCharacter, Count:=-1 
rng.ContentControls.Add (wdContentControlCheckBox) 
+0

它的工作。我不敢相信我之前有多接近它,但是通過釘住它。 所有我必須做的與你的單詞vba添加oWord.Selection就地選擇,我可以添加儘可能多的框,因爲我想。 – Chasester

+0

我最終通過修改來使用它。而不是選擇我剛剛使用UBound和分裂它。 – Chasester