【问题标题】:Compile Error: Method or data member not found, VBA编译错误:找不到方法或数据成员,VBA
【发布时间】:2020-06-02 21:27:29
【问题描述】:

我在 Microsoft Word 中使用 ActiveX 命令按钮来执行以下任务:

  1. 为一系列表格添加 ActiveX 标签
  2. 重命名插入的 ActiveX 标签
  3. 使用 Excel 工作簿中的数据填充 ActiveX 标签的标题

我将 ActiveX 标签重命名为 "FY" & seq,其中 seq 是一个数字序列。例如,重命名的标签可能是“FY1”。在第 3 步中,我的代码使用“FY1”(ThisDocument.FY1.Caption = rw.Cells(1).Value),但代码不会运行,我会收到 Compile Error: Method or data member not found 消息。

我是否必须调用新的 Sub 才能识别我的标签?有没有办法通过单击 ActiveX 按钮来运行整个代码?

Private Sub CommandButton1_Click()

Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
Dim rng As Excel.Range, m, rw As Excel.Range
Dim num As Integer
Dim TableNo As Integer
Dim seq As Integer
Dim ctl As MSForms.Label
Dim ils As Word.InlineShape

Set objExcel = New Excel.Application
Set exWb = objExcel.Workbooks.Open("O:\Documents\Database.csv")
Set rng = exWb.Sheets("FY1819_DatabaseExtracted").Cells
TableNo = ActiveDocument.Tables.Count
num = 3
seq = 1

'' Now, create all FY labels
Do
    Set ils = ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY" & seq
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

'''' Match to Excel Database
m = objExcel.Match(ThisDocument.Code1.Caption, rng.Columns(3), 0)

If Not IsError(m) Then
    Set rw = rng.Rows(m) '<< get the matching row as a Range
    ThisDocument.FY1.Caption = rw.Cells(1).Value 'value from colA
End If

Set exWb = Nothing

End Sub

我的错误发生在ThisDocument.FY1.Caption = rw.Cells(1).Value。 'FY1' 无法识别。

【问题讨论】:

  • 打开文档后,它看起来像seq = 2,然后seq 在它下面的循环中递增。文档中肯定有FY1 还是应该以FY2 开头?
  • 刚刚编辑seq 所以它= 1。错误信息仍然出现。
  • ThisDocument.FY1.Caption 需要能够编译之前您的代码可以运行添加控件 - 这是一个问题。也许看看这里如何避免硬编码名称 - stackoverflow.com/questions/24088721/…

标签: excel vba ms-word activex


【解决方案1】:

以下是如何更改代码的简化示例:

Private Sub CommandButton1_Click()

    Dim obj, ctl, ils As Word.InlineShape

    'add a control and set its name          
    Set ils = ActiveDocument.Tables(1).Cell(1, 1).Range. _
                  InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY1"
    'consider setting the caption here?


    'ThisDocument.FY1.Caption = "Hello" '<< will not compile

    'alternate approach
    Set obj = GetControl(ActiveDocument, "FY1")
    If Not obj Is Nothing Then
        obj.Caption = "Hello"
    End If

End Sub

'get a control by name
Function GetControl(doc As Document, conName As String) As Object
    Dim rv As Object, obj
    For Each obj In doc.InlineShapes
        If obj.OLEFormat.Object.Name = conName Then
            Set rv = obj.OLEFormat.Object
            Exit For
        End If
    Next obj
    Set GetControl = rv
End Function

【讨论】:

  • 完美!我使用了第一个选项,将标题命名为ctl.Caption = rw.Cells(7).Value
  • 是的,这当然是最简单的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多