我在工作中使用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
没有保持固定?