公共变量返回空字符串

时间:2017-08-02 23:55:00

标签: vba global-variables

我正在使用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为什么没有保持不变的任何想法?

2 个答案:

答案 0 :(得分:2)

您在运行时动态地向相同的模块添加子例程。这将触发项目的重置 - 结束程序执行,并清除所有变量。

如果您尝试手动将程序添加到正在运行的模块(在调试模式下),您将收到此警告:

enter image description here

但是,在以编程方式添加代码时,您不会收到警告。

在任何情况下,当您可能希望将其添加到托管控件的工作表模块时,您将该过程添加到ThisWorkbook模块。

答案 1 :(得分:0)

我遇到了同样的问题,尝试像这样将变量声明为Global而不是Public

Global theName As String
相关问题