Ошибка компиляции: метод или элемент данных не найден, VBA - PullRequest
0 голосов
/ 18 февраля 2020

Я использую командную кнопку ActiveX в Microsoft Word для выполнения следующих задач:

  1. Добавление меток ActiveX в серию таблиц
  2. Переименование вставленных меток ActiveX
  3. Заполните заголовки меток ActiveX данными из рабочей книги Excel

Я переименую метки 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' не распознан.

1 Ответ

1 голос
/ 18 февраля 2020

Вот упрощенный пример того, как изменить ваш код:

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
...