我正在使用VBA创建一个文档(因为这是我在工作中唯一可以使用的东西)。我的变量在设置后返回一个空字符串。我试图通过方法帽将数据传递给用户表单,并在运行时动态生成。
我在ThisDocument模块的顶部设置了这样的变量
Public theName As String
然后在选中复选框时运行
With tblNew
'.Cell(Row:=rowCount, Column:=2).Merge MergeTo:=.Cell(Row:=rowCount, Column:=3)
.Rows(rowCount).SetHeight RowHeight:=InchesToPoints(0.35), HeightRule:=wdRowHeightExactly
.Cell(Row:=rowCount, Column:=1).SetWidth ColumnWidth:=InchesToPoints(0.75), RulerStyle:=wdAdjustNone
.Cell(Row:=rowCount, Column:=2).SetWidth ColumnWidth:=InchesToPoints(2.08), RulerStyle:=wdAdjustNone
.Cell(Row:=rowCount, Column:=3).SetWidth ColumnWidth:=InchesToPoints(1), RulerStyle:=wdAdjustNone
.Cell(Row:=rowCount, Column:=4).SetWidth ColumnWidth:=InchesToPoints(2), RulerStyle:=wdAdjustNone
.Cell(Row:=rowCount, Column:=5).SetWidth ColumnWidth:=InchesToPoints(1.85), RulerStyle:=wdAdjustNone
.Cell(rowCount, 1).Range.InsertAfter "Name:"
.Cell(rowCount, 3).Range.InsertAfter "Type:"
.Cell(rowCount, 2).Range.InlineShapes.AddOLEControl ClassType:="Forms.TextBox.1"
Set myCB = .Cell(rowCount, 4).Range.InlineShapes.AddOLEControl(ClassType:="Forms.TextBox.1")
Dim uofCode As String
Dim doc As Word.Document
Set doc = ActiveDocument
theName = myCB.OLEFormat.Object.Name
MsgBox theName ‘this message works fine
uofCode = "Private Sub " & myCB.OLEFormat.Object.Name & "_GotFocus()" & vbCrLf & _
vbCr & "Load uofForm" & vbCr & "uofForm.Tag = theName" & vbCr & "uofForm.Show" & vbCr & vbCrLf & _
"End Sub"
doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString uofCode
End With
我使用此行theName
设置变量theName = myCB.OLEFormat.Object.Name
,并确保将其设置为使用MsgBox进行测试MsgBox theName
此消息正常工作。现在问题是当它生成函数时变量为空。变量theName
为什么没有保持不变的任何想法?