为什么说Sub TxtInTab内的WordApp变量没有定义(VB调用VBA)
按启动就出现Sub TxtInTab内的WordApp变量没定义。
不过如果把Dim myDoc, WordApp As Object放在Option Explicit内就解决了问题,但
本人一定要将Dim myDoc, WordApp As Object放在command2中。
有问题的代码如下:
Option Explicit
Dim W As Integer
Private Sub Command2_Click()
Dim myDoc, WordApp As Object
Set WordApp = CreateObject("Word.Application")
Set myDoc = WordApp.Documents.Add()
WordApp.Visible = False ' True
WordApp.Selection.TypeParagraph '回车
WordApp.ActiveDocument.Tables.Add Range:=WordApp.Selection.Range, NumRows:=7, NumColumns:=6, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed
WordApp.ActiveDocument.Tables(1).Select '选中整个表格
WordApp.Selection.Rows.HeightRule = wdRowHeightExactly '设置行高
WordApp.Selection.Rows.Height = CentimetersToPoints(1.03) '设置行高
WordApp.Selection.Cells.VerticalAlignment = wdCellAlignVerticalCenter '垂直居中
WordApp.ActiveDocument.Tables(1).Rows.Alignment = wdAlignParagraphCenter '表格页面居中
Call TxtInTab(1, 2, 3, 4, 5)
WordApp.ActiveDocument.SaveAs App.Path & "\1.doc"
WordApp.Quit '退出
Set WordApp = Nothing
End Sub
Sub TxtInTab(Txt1, Txt2, Txt3, Txt4, Txt5)
WordApp.ActiveDocument.Tables(1).Rows(W).Select
WordApp.ActiveDocument.Tables(1).Cell(W, 1).Range.Text = Txt1
WordApp.ActiveDocument.Tables(1).Cell(W, 2).Range.Text = Txt3
WordApp.ActiveDocument.Tables(1).Cell(W, 3).Range.Text = Txt2
WordApp.ActiveDocument.Tables(1).Cell(W, 4).Range.Text = Txt4
WordApp.ActiveDocument.Tables(1).Cell(W, 5).Range.Text = Txt5
End Sub
[解决办法]
Sub TxtInTab(WordApp as object,Txt1 as string, Txt2 as string, Txt3 as string, Txt4 as string, Txt5 as string)
WordApp.ActiveDocument.Tables(1).Rows(W).Select
WordApp.ActiveDocument.Tables(1).Cell(W, 1).Range.Text = Txt1
WordApp.ActiveDocument.Tables(1).Cell(W, 2).Range.Text = Txt3
WordApp.ActiveDocument.Tables(1).Cell(W, 3).Range.Text = Txt2
WordApp.ActiveDocument.Tables(1).Cell(W, 4).Range.Text = Txt4
WordApp.ActiveDocument.Tables(1).Cell(W, 5).Range.Text = Txt5
End Sub