我很长时间以来第一次使用VBA,需要一些帮助才能在文档中添加表格。
目前有问题的一行是
.Cell(1, x).Range.Select
我得到的错误是对象变量或没有设置块变量。而对于我的生活,我无法看到我在这个问题上的错误。
我正在传递一个三维字符串数组,我希望将其传递到一个表中,这是我目前正在处理的代码
Private Sub Create_Sized_Table_Multi_Column(i_Rows As Integer, i_Columns As Integer)
'create a table
Set t_newtable = ActiveDocument.Tables.Add(Selection.Range, i_Rows, i_Columns)
End Sub
Private Sub BuildTable(arr() As String, colCount As Integer, bookMark As String)
Dim t_newtable As Table
Dim i_Fund_Quantity As Integer
Dim i_Rows_Required As Integer
Dim i_Columns_Required As Integer
'Number of funds is the upperbound + 1 to allow for the zero relative
i_Fund_Quantity = UBound(arr) + 1
'header Row
i_Rows_Required = UBound(arr) + 1
'Number of columns
i_Columns_Required = colCount
'Add a table - this table will contain moved funds
'creates the table dimensioned by i_rows x i_column
Create_Sized_Table_Multi_Column i_Rows_Required, i_Columns_Required
'Now populate the header row
With t_newtable
For x = 0 To i_Columns_Required
.Cell(1, x).Range.Select
If x = 1 Then
Set_Table_Headers "Existing Fund"
ElseIf x = 2 Then
Set_Table_Headers "Customer Name"
ElseIf x = 3 Then
Set_Table_Headers "Switch To"
ActiveDocument.Bookmarks.Add ("bk_Switched_Table")
End If
Next
End With
'Populate the table with the fund details
''//sp write to table here
With t_newtable
'Position cursor at first insertion point
'ActiveDocument.Bookmarks("bk_Switched_Table").Select
'Now create a loop
For i_Loop_Rows = 0 To UBound(arr)
Set_Table_Rows
Selection.TypeText arr(i, 0)
Selection.MoveRight UNIT:=wdCell
Selection.TypeText arr(i, 1)
Selection.MoveRight UNIT:=wdCell
Selection.TypeText arr(i, 2)
t_newtable.Columns(3).Select
t_newtable.Columns.AutoFit
Selection.Collapse Direction:=wdCollapseEnd
Next
End With
ActiveDocument.Bookmarks(bookMark).Select
Selection.TypeParagraph
Selection.TypeText s_Text
Selection.TypeParagraph
ActiveDocument.Bookmarks.Add (bookMark)
End Sub
如果有人能够对此进行评论并让我知道我哪里出错了以及我需要改变什么,我将不胜感激。
感谢
西蒙
答案 0 :(得分:1)
您永远不会在t_newtable
子广告中设置BuildTable
。如果你必须在其他地方创建你的桌子,那么你必须
Set t_newtable = ActiveDocument.Tables(indexOfYourTable)
将t_newtable
实例化为您想要的对象。 注意: indexOfYourTable
基于1
,而不是0
。
或强>
您可以将代码行放在Create_Sized_Table_Multi_Column
子内的BuildTable
子内,并将所需的变量传递到BuildTable
子内。
答案 1 :(得分:1)
您在过程newtable
中声明了t _ Create_Sized_Table_Multi_Column
,因此它将仅限于该范围。如果要调用该过程,让它创建表,然后使其可用于调用它的代码,则需要将Sub
更改为Function
并让函数返回表。
例如:
Private Function Create_Sized_Table_Multi_Column(i_Rows As Integer, _
i_Columns As Integer) As Table
'create a table
Set Create_Sized_Table_Multi_Column = ActiveDocument.Tables.Add( _
Selection.Range, i_Rows, i_Columns)
End Function
然后你就像这样使用它(为了清晰起见,代码缩短了):
Private Sub BuildTable(arr() As String, colCount As Integer, bookMark As String)
Dim t_newtable As Table
'Add a table - this table will contain moved funds
'creates the table dimensioned by i_rows x i_column
Set t_newtable = Create_Sized_Table_Multi_Column(i_Rows_Required, _
i_Columns_Required)
End Sub
请注意函数调用周围添加的括号。当从呼叫中返回某些内容时,这些是必需的。