Меню

Invalid use of property vba ошибка

I have the Student class in VBA (Excel) implemented as follows

Option Explicit

Private name_ As String
Private surname_ As String
Private marks_ As New Collection


Public Property Get getMean() As Single

    Dim sum As Double
    Dim mark As Double
    Dim count As Integer

    For Each mark In marks_
        sum = sum + mark
        count = count + 1
    Next mark

    getMean = sum / count

End Property

Public Property Let setName(name As String)
    name_ = name
End Property

Public Property Get getName() As String
    getName = name_
End Property

Public Property Let setSurname(surname As String)
    surname_ = surname
End Property

Public Property Get getSurname() As String
    getSurname = surname_
End Property

Then I have a main sub where I write:

Dim stud1 As New Student

stud1.setName "Andy"

I got a compile error on stud1.setName "Andy" : Invalid use of property.
I don’t understand why. Any Idea, please?

Community's user avatar

asked Feb 1, 2014 at 20:06

mStudent's user avatar

2

Since it’s a property (not method) you should use = to apply a value:

Dim stud1 As New Student

stud1.setName = "Andy"

BTW, for simplicity, you can use the same name for get and set properties:

Public Property Let Name(name As String)
    name_ = name
End Property

Public Property Get Name() As String
    Name = name_
End Property

and then use them as follows:

Dim stud1 As New Student
'set name
stud1.Name = "Andy"
'get name
MsgBox stud1.Name

AAA's user avatar

AAA

3,4501 gold badge14 silver badges31 bronze badges

answered Feb 1, 2014 at 20:07

Dmitry Pavliv's user avatar

Dmitry PavlivDmitry Pavliv

35.1k13 gold badges79 silver badges80 bronze badges

3

Вопрос:

Я знаю, что есть тонны нитей и вопросов об этом, и это довольно очевидно, как правило, где ошибка. Большинство людей не используют ключевое слово SET при перемещении объектов. Я.

Вот что происходит:

Это находится на листе excel, поэтому я сделал небольшой набор функций для отслеживания столбцов и создания индекса, чтобы каждый раз, когда приложение запускает его, он будет переиндексировать столбцы, чтобы я мог делать такие вещи, как .Cells(row_num, pCust_index("custID")) в случае изменения столбца.

У меня есть форма custContagions. Это просто небольшое модальное окно, которое позволяет пользователям добавлять/удалять/редактировать зараженный клиентом статус. Он содержит свойство:

Private pCust_index as dictionary

Он также содержит этот набор свойств:

Public Property Set set_cust_index(ByRef custIndex As Dictionary)
Set pCust_index = New Dictionary
Set pcust_index = custIndex
End Property

Довольно прямо вперед? Принимает объект словаря, сбрасывает мой индекс и указывает на существующий переданный объект.

Теперь, в вызывающей форме у меня есть другая сторона:

Private Sub newCustContagious_LBL_Click()
Dim contForm as New custContagions
Call contForm.set_cust_index(pCust_index)  'note pCust_index is a private here too
Call contForm.Show
...

Я получаю ошибку Invalid Use of Property compiler при вызове set_cust_index.

Что я упустил?

Лучший ответ:

Большинство людей не используют ключевое слово SET при перемещении объектов вокруг

Затем они не движутся вокруг объектов. Ключевое слово Set – способ перемещения объекта вокруг.
Существует также CopyMemory чтобы напрямую копировать ObjPtr, но я не считаю, что большинство людей это делают.

Довольно прямо вперед?

Не совсем. Вы создаете словарь, немедленно отбрасываете его и заменяете другим словарем, переданным в качестве параметра. Вы должны удалить первую из двух строк и создать параметр ByVal:

Public Property Set set_cust_index(ByVal custIndex As Dictionary)
    Set pcust_index = custIndex
End Property

Я получаю ошибку компилятора Invalid Use of Property

Вы объявили свойство, а затем использовали его как суб. С собственностью вы должны были сделать:

Set contForm.set_cust_index = pCust_index

В этот момент имя set_cust_index не выглядит великолепно. Это сделало бы разумное имя для sub (Public Sub set_cust_index(ByVal custIndex As Dictionary)), но для свойства вам было бы лучше с Public Property Set cust_index(ByVal custIndex As Dictionary).

  • Remove From My Forums
  • Вопрос

  • I am not a skilled code writer. Please respond as you would to a 10 year old with your explanations. 

    I created a user form in VBA through Office 365 Word 2016. The form is an audit questionnaire with only text boxes and combo option boxes. The goal is to have the form auto generate an audit report. 

    I followed instructions and copied the code format from a website. When I go to debug>compile normal- I get an error message that says «Compile error: Invalid use of property». This is on one line of code for a textbox. txtocip Value =
    «a»  The codes for the other text boxes are set the same way but do not show this error. 

    How do I correct this? I do not fully grasp the concept of properties and how it relates to coding. 

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #2

What is the purpose of that «f9» in there for? It shouldn’t be there.
You can also combine the two rows toegether (you seldom need a «.Select» followed by a «Selection.»).
So all of this:

Code:

Range("f9").Select
   ActiveCell.[COLOR=#ff0000]Formula[/COLOR] "f9" = "=IF(OR(K9=0,m9=0,m9=""misc.""),m9,m9-k9)"
    Range("G9").Select
    ActiveCell.Formula "g9" = "=IF(OR(j9=0,n9=0),n9,n9-j9)"

can be combined like this:

Code:

Range("f9").Formula = "=IF(OR(K9=0,m9=0,m9=""misc.""),m9,m9-k9)"
Range("G9").Formula = "=IF(OR(j9=0,n9=0),n9,n9-j9)"

Last edited: Mar 29, 2016

  • #3

Hi

Remove the «f9» and «g9» and your code should work OK.

HTH

Dave

  • #4

Thanks Joe & Dave — I’m not sure it works because now I’m stuck the first part of the code.
I have column «I» which a person will enter a {y, n, ok}.
However, I want these to be changed via formatting. I want the y = green smiley face. I want n = red x. And I want ok = blue checkmark.
I used 3 types of formatting as listed — see very beginning of code below. However, when I try to run the code now I get a Run-time error ‘424’: Object required. I can’t remember now if it was the 1st or 2nd line of the code see green highlights. Also, when it stepped on I came to another error (see purple highlight). The error was «Compile error: Invalid use of property. The orange highligt is this error «Runtime error 1004: Application define or Object defined error»
Any ideas?

Rich (BB code):

Sub Monthly_NOs_Update()
'
' Monthly_NOs_Update Macro
' Column F-ColumnD Column G-ColumnC
'
' Keyboard Shortcut: Ctrl+m
   If Target.Column = 9 Then
        If Target.Value = "y" Then
            With Target
                .Font.Name = "Carta"
                .Value = "J"
            End With
        End If
        If Target.Value = "n" Then
            With Target
                .Font.Name = "Bookshelf Symbol 7"
                .Value = "i"
            End With
        End If
        If Target.Value = "ok" Then
            With Target
                .Font.Name = "ZDingbats"
                .Value = "4"
            End With
        End If
    End If
    Columns("C:G").Select
    Selection.Copy
    Range("j9:n9").Select
    ActiveSheet.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
   Range("f9").Formula = "=IF(OR(K9=0,m9=0,m9=""misc.""),m9,m9-k9)"
Range("G9").Formula = "=IF(OR(j9=0,n9=0),n9,n9-j9)"
    Range("F9:G9").Select
    Selection.Copy
    Range("F10:F17").Select
    ActiveSheet.Paste
    Range("F19:F23").Select
    ActiveSheet.Paste
    Range("F25:F30").Select
    ActiveSheet.Paste
    Range("F32:F36").Select
    ActiveSheet.Paste
    Range("F37:F39").Select
    ActiveSheet.Paste
    Range("F40:F42").Select
    ActiveSheet.Paste
    Range("F43:F45").Select
    ActiveSheet.Paste
    Range("F46:F48").Select
    ActiveSheet.Paste
    Range("f49:f51").Select
    ActiveSheet.Paste
    Range("f53:f64").Select
    ActiveSheet.Paste
    Columns("F:G").Select
    Range("j10:n10").Select
    Selection.Copy
    Columns("F:G").Select
    ActiveSheet.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False
    Columns("j:n").Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlToLeft
Dim rng As Range
Application.ScreenUpdating = False
For Each rng In Range("c9:d64")
    With rng
        If .Value > 0 Then .ClearContents
        If .Offset(, x).Value = 0 Then .Offset(, x).ClearContents
    End With
Next rng
Application.ScreenUpdating = True
    fName = ActiveWorkbook.FullName
    fName = Left(fName, InStrRev(fName, ".") - 1) & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
   Application.ScreenUpdating = False
    Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    'insert first sheet name in next line
    If Not ws.Name = "Sheet1" Then ws.PrintOut
Next ws
End Sub

Last edited: Mar 29, 2016

  • #5

I’m sure Joe4 will correct me if I’m wrong, but it looks like you’re running this as a standalone macro…Target would need to be declared as something, it would work OK if you were running from a worksheet event.

The next bit might be down to you selecting the entire column and then pasting into row 9, that size of the copied range wouldn’t fit.

If you could put in words what it’s to do I’ll try and tidy it up for you ;)

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #6

I’m sure Joe4 will correct me if I’m wrong, but it looks like you’re running this as a standalone macro…Target would need to be declared as something, it would work OK if you were running from a worksheet event.

Good catch. I missed that.

«Target» is used in Event Procedures. I suppose you could use it as a variable in standalone procedure, though you would need to define it, which you haven’t done (so «Target» actually is nothing in your procedure).

  • #7

I am trying to Copy & Paste as Value Columns C:G to Columns J:N.
I then want to put a formula in f9 and g9. (This you have already helped me on).
Then I want to copy the formulas in f9 and g9 down through the various groups of rows. Ultimate end is for all rows in columns C:D are cleared for next months data input.
Once this is done, I want to copy & paste as value C:G and Delete J:N.
I would like for the clerk to be able to enter «y», «n», «ok» and have the code change the formatting to reflect a green «smiley face»,a red «X» and a blue «checkmark».
Then I would like to clear contents for any data entered into the same various group of rows but only in Columns C & D.
Finally, I would like the file to be saved.
Thanking you all in advance for any help!

Last edited: Mar 29, 2016

  • #8

Can you all explain what you mean by a «standalone macro» (vs. what) and Event procedures and variable in a standalone macro. I’m trying very hard to learn VBA on my own so I needn’t bother good folks like you all. I would like to be one of the people helping others. Someday perhaps.

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #9

Event Procedure code is a «special» kind of VBA code. It is VBA that is automatically triggered upon some «event» happening, like opening the file, changing a cell, selecting a cell, saving a file, etc. In order for it to work, it needs to follow strict rules, specifically it has to be located in the proper Workbook or Worksheet module and must be named a certain way (there is no flexibility in that). See here for more details on it: Events In Excel VBA

Then there are procedures that you create yourself and put in standard modules. These can be named most anything you like (following some basic naming convention rules). These do not run automatically. Usually, your assign these to a keyboard shortcut, a command button, or simply run them through the Macro menu. The main point being, is you need to explicitly do something in order to run these macros. User Defined Functions also fall into this category.

  • #10

Hi dstepan

Am I to take it there will be three happenings here?

1. You set up the spreadie.
2. Your clerk enters the y, n, ok (deleting the values from columns C&D on that row)
3. You finalise the spreadie

Is that the general run of it?

Thanks

Dave

Anyone know what’s wrong with the code here? Thanks in advance!

    Sub Clear_data()* Getting an error here
    
    Dim rng1 As Variant 'this is to save range where the FX rates will paste over
    Dim rng2 As Variant 'this is to save range of FX rates data
    Dim rng3 As Variant 'this is to save range of NAV and CB data
    Dim rng4 As Variant
    
    Set rng2 = Sheets("Rate").Range("b3:g28")
    Set rng1 = Sheets("Rate").Range("I3:n28")
    Set rng3 = Sheets("transfer").Range("C11:G22")
    Set rng4 = Sheets("REC").Range("K9:O20")
    
        Application.Goto rng2 'copies over the prior's FX rate over for  reconciliation
        Selection.Copy
        Application.Goto rng1
        Selection.pastespecial Paste:=xlPasteValues
        Selection.pastespecial Paste:=xlPasteFormats
        
        Application.Goto rng3
        Selection.Copy
        Application.Goto rng4
        Selection.pastespecial Paste: xlPasteValues
        Application.Goto Sheets("Transfer").Range("A1")

End Sub

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    Популярные разделы FAQ:    user posted image Общие вопросы    user posted image Особенности VBA-кода    user posted image Оптимизация VBA-кода    user posted image Полезные ссылки


    1. Старайтесь при создании темы указывать в заголовке или теле сообщения название офисного приложения и (желательно при работе с Office 95/97/2000) его версию. Это значительно сократит количество промежуточных вопросов.
    2. Формулируйте вопросы как можно конкретнее, вспоминая (хотя бы иногда) о правилах ВЕЛИКОГО И МОГУЧЕГО РУССКОГО ЯЗЫКА, и не забывая, что краткость — сестра таланта.
    3. Не забывайте использовать теги [сode=vba] …текст программы… [/code] для выделения текста программы подсветкой!
    4. Темы с просьбой выполнить какую-либо работу полностью за автора здесь не обсуждаются и переносятся в раздел ПОМОЩЬ СТУДЕНТАМ.

    >
    В чем ошибка?

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    28.03.07, 05:56

      Full Member

      ***

      Рейтинг (т): 5

      Программа открывает файл, считывает один за другим параграфы и заполняет с помощью процедуры FillVisitUserWithLogData некую структурку visitUser полученными данными.

      ExpandedWrap disabled

        Dim docLogFile As Document

        Dim rngLogFileRange As Range

        Dim parLogFile As Paragraph

        Set docLogFile = Documents.Open(FileName:=strLogFileName, ReadOnly:=True, Visible:=False)

        For Each parLogFile In docLogFile.Paragraphs

            Set rngLogFileRange = parLogFile.Range.Select

            FillVisitUserWithLogData rngRange:=rngLogFileRange, visitUser:=visitUser

        End For

        ‘—————————————————-

        Private Sub FillVisitUserWithLogData(rngRange As Range, visitUser As Visit)

            ‘…

            ‘…

            ‘…

        End Sub

      Во время запуска программы на выполнение возникает ошибка: «Compile error: ByRef argument type mismatch», при этом подсвечивается параметр rngLogFileRange в строке вызова процедуры FillVisitUserWithLogData. Не могу понять что приводит к ошибке. Вроде, все типы совпадают.


      Krasnaja Shapka



      Сообщ.
      #2

      ,
      28.03.07, 06:26

        Full Member

        ***

        Рейтинг (т): 18

        а что имелось ввиду под этим: Set rngLogFileRange = parLogFile.Range.Select?
        select — это метод, он ничего не возвращает, поэтому у тебя твоя range переменная = Nothing — вот и ошибка

        п.с. на будующее юзай пошаговый запуск (F8) со включенными locals window (там отображаются значения всех переменных в данный момент) и watches window при необходимости (туда можно вставить дополнительные конструкции и отслеживать их значение)…

        Сообщение отредактировано: Krasnaja Shapka — 28.03.07, 06:31


        awax



        Сообщ.
        #3

        ,
        28.03.07, 08:48

          Full Member

          ***

          Рейтинг (т): 5

          Цитата

          а что имелось ввиду под этим: Set rngLogFileRange = parLogFile.Range.Select?
          select — это метод, он ничего не возвращает, поэтому у тебя твоя range переменная = Nothing — вот и ошибка

          При помощи Set rngLogFileRange = parLogFile.Range.Select я хотел установить рандж в 1 параграф, ну и передавать его процедуре для обработке. А Select для того, чтобы весь этот процесс наблюдать визуально, для контроля (где-то вычитал про такой прием).
          Так, как сделать, чтобы все было ОК, чтобы возвращался рандж?


          Krasnaja Shapka



          Сообщ.
          #4

          ,
          28.03.07, 09:31

            Full Member

            ***

            Рейтинг (т): 18

            разбей это на два оператора…

            Set rngLogFileRange = parLogFile.Range
            и
            parLogFile.Range.Select (или rngLogFileRange.select)

            Добавлено 28.03.07, 09:33
            а можешь вообще вызвать

            FillVisitUserWithLogData parLogFile.Range, visitUser

            и избавишься от лишней переменной… :)

            Сообщение отредактировано: Krasnaja Shapka — 28.03.07, 09:34


            awax



            Сообщ.
            #5

            ,
            28.03.07, 12:39

              Full Member

              ***

              Рейтинг (т): 5

              Цитата

              разбей это на два оператора…

              Set rngLogFileRange = parLogFile.Range
              и
              parLogFile.Range.Select (или rngLogFileRange.select)

              Не-а, твой вариант тоже не работает. Кажется я нашел причину ошибки. Переменная rngLogFileRange объявляется вместе с еще одной:

              ExpandedWrap disabled

                Dim rngLogFileRange, rngRange As Range

              А если их объявить так:

              ExpandedWrap disabled

                Dim rngLogFileRange As Range

                Dim  rngRange As Range

              то все работает правильно. Объяснения у меня этому нет.

              P.S.
              Появилась другая ошибка:

              ExpandedWrap disabled

                Dim tblTargetTable As table

                    ‘ …

                    ‘ …

                    ‘ …

                Set tblTargetTable = InsertNextOutputTable(docDocument:=docActive, intTableIndex:=visitUser.intIndex)

                ‘————————————

                Private Function InsertNextOutputTable(docDocument As Document, intTableIndex As Integer)

                   Dim tblTable As table

                    ‘ …

                    ‘ …

                    ‘ …

                   InsertNextOutputTable = tblTable

                End Function

              Компилятор выдает ошибку 13. Мол, опять с типами косяк какой-то. Подсвечивает всю строку целеком. В чем дело?


              pvr



              Сообщ.
              #6

              ,
              28.03.07, 14:04

                Junior

                *

                Рейтинг (т): 9

                В VBA, в отличие от VB, тип переменной нужно указывать после ее объявлеия.
                Если тип переменной опущен, то ей автоматически присваивается тип Variant, НЕ OBJECT.
                Function InsertNextOutputTable надо объявить как AS TABLE ( или OBJECT)


                Krasnaja Shapka



                Сообщ.
                #7

                ,
                28.03.07, 16:05

                  Full Member

                  ***

                  Рейтинг (т): 18

                  то у вас

                  Цитата awax @ 28.03.07, 05:56

                  Dim rngLogFileRange As Range

                  то

                  Цитата awax @ 28.03.07, 12:39

                  Dim rngLogFileRange, rngRange As Range

                  вы определитесь, а? :)

                  вы пробовали свой макрос по F8 прогнать или проще в форуме спрашивать? :)))


                  awax



                  Сообщ.
                  #8

                  ,
                  29.03.07, 07:22

                    Full Member

                    ***

                    Рейтинг (т): 5

                    Цитата pvr @ 28.03.07, 14:04

                    Function InsertNextOutputTable надо объявить как AS TABLE ( или OBJECT)

                    Это как? Table Function InsertNextOutputTable? Как в сях?

                    -Added 29.03.07, 07:40

                    Цитата Krasnaja Shapka @ 28.03.07, 16:05

                    то у вас

                    Цитата awax @ 28.03.07, 05:56

                    Dim rngLogFileRange As Range

                    то

                    Цитата awax @ 28.03.07, 12:39

                    Dim rngLogFileRange, rngRange As Range

                    вы определитесь, а? :)

                    вы пробовали свой макрос по F8 прогнать или проще в форуме спрашивать? :)))

                    Прошу прощения за несогласованность. Дело в том, что для краткости и четкости я убираю все то, что, как мне кажется, не относиться непосредственно к вопросу. Поэтому я убрал rngRange, но позже понял, что, возможно, этот самый rngRange и является причиной возникновения ошибки. Насколько я теперь понимаю (спасибо pvr!!!) при объявлении

                    ExpandedWrap disabled

                      Dim rngLogFileRange, rngRange As Range

                    переменная rngLogFileRange объявляется как variant. В моем случае это недопустимо.
                    А что касается F8, то я, безусловно, пользуюсь этой возможностью, но до определенного момента, пока не возникает ошибка, так что полностью прогнать макрос не получается.


                    pvr



                    Сообщ.
                    #9

                    ,
                    29.03.07, 08:14

                      Junior

                      *

                      Рейтинг (т): 9

                      Цитата

                      Цитата (pvr @ Вчера, 17:04)
                      Function InsertNextOutputTable надо объявить как AS TABLE ( или OBJECT)

                      Это как? Table Function InsertNextOutputTable? Как в сях?

                      Надо юзать Help или учебник какой….

                      ExpandedWrap disabled

                        Private Function InsertNextOutputTable(docDocument As Document, intTableIndex As Integer) As Table


                      awax



                      Сообщ.
                      #10

                      ,
                      30.03.07, 07:03

                        Full Member

                        ***

                        Рейтинг (т): 5

                        Спасибо, pvr, но компилятор подкинул новую задачку. Функция InsertNextOutputTable создает таблицу и возвращает ссылку на нее.

                        ExpandedWrap disabled

                          Private Function InsertNextOutputTable(docDocument As Document, intTableIndex As Integer) as table

                              Dim tblTable As table

                              Dim rngTable As Range

                              ‘ …

                              ‘ …

                              ‘ …

                              Set tblTable = docDocument.Tables.Add(Range:=rngTable, NumRows:=1, NumColumns:=5)

                              InsertNextOutputTable = tblTable

                          End Function

                        Используется ф-я следующим образом:

                        ExpandedWrap disabled

                          Dim tblTargetTable As table

                              ‘ …

                              ‘ …

                              ‘ …

                          Set tblTargetTable = InsertNextOutputTable(docDocument:=docActive, intTableIndex:=visitUser.intIndex)

                        Во время прогона макроса, при входе в функцию, компилятор сразу останавливает выполнение программы, подсвечивает InsertNextOutputTable в последнем выражении функции и выдает ошибку Compile error: Invalid use of property. Все типы определены и совпадают. В чем дело? Учебник по VBA ответа на этот вопрос не дает ;)

                        Profi

                        Old Bat



                        Сообщ.
                        #11

                        ,
                        30.03.07, 10:57

                          Moderator

                          *****

                          Рейтинг (т): 128

                          ExpandedWrap disabled

                            Set InsertNextOutputTable = tblTable

                          , но лучше сразу

                          ExpandedWrap disabled

                            Set InsertNextOutputTable = docDocument.Tables.Add(Range:=rngTable, NumRows:=1, NumColumns:=5)

                          Цитата awax @ 30.03.07, 07:03

                          Учебник по VBA ответа на этот вопрос не дает

                          :huh: что за источник ?? см. создание ссылки на объект


                          awax



                          Сообщ.
                          #12

                          ,
                          30.03.07, 12:12

                            Full Member

                            ***

                            Рейтинг (т): 5

                            Цитата

                            что за источник ??

                            VBA for Dummies :yes:

                            Profi

                            Old Bat



                            Сообщ.
                            #13

                            ,
                            30.03.07, 13:36

                              Moderator

                              *****

                              Рейтинг (т): 128

                              гм, попользуй ссылочку, много чего полезного есть
                              http://word.mvps.org/FAQs/MacrosVBA/


                              awax



                              Сообщ.
                              #14

                              ,
                              02.04.07, 07:20

                                Full Member

                                ***

                                Рейтинг (т): 5

                                Цитата Old Bat @ 30.03.07, 10:57

                                ExpandedWrap disabled

                                  Set InsertNextOutputTable = tblTable

                                , но лучше сразу

                                ExpandedWrap disabled

                                  Set InsertNextOutputTable = docDocument.Tables.Add(Range:=rngTable, NumRows:=1, NumColumns:=5)

                                Спасибо за подсказку. Все работает. Ссылку почитаю. Держи плюс ;)

                                0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                0 пользователей:

                                • Предыдущая тема
                                • VB for Application
                                • Следующая тема

                                Рейтинг@Mail.ru

                                [ Script execution time: 0,0498 ]   [ 16 queries used ]   [ Generated: 28.01.23, 21:07 GMT ]  

                                • Home
                                • VBForums
                                • Visual Basic
                                • Visual Basic 6 and Earlier
                                • [RESOLVED] Compile error: Invalid use of property

                                1. Jul 9th, 2010, 06:46 AM


                                  #1

                                  Arispan is offline

                                  Thread Starter


                                  Lively Member

                                  Arispan's Avatar


                                  Resolved [RESOLVED] Compile error: Invalid use of property

                                  Hello everyone,

                                  I’m making a big project (my biggest project) but I get a «Compile error: Invalid use of property» message.

                                  Here’s my code:

                                  vb Code:

                                  1. Private CForm As Form

                                  2. Public Sub Initialize(Child As Form)

                                  3. CForm = Child 'This line gives the error

                                  4. End Sub

                                  When I call my «Initialize» sub from another form, I get this error.
                                  Can someone help me ?

                                  Last edited by Arispan; Jul 9th, 2010 at 06:51 AM.


                                2. Jul 9th, 2010, 06:50 AM


                                  #2

                                  Re: Compile error: Invalid use of property


                                3. Jul 9th, 2010, 06:55 AM


                                  #3

                                  Arispan is offline

                                  Thread Starter


                                  Lively Member

                                  Arispan's Avatar


                                  Re: Compile error: Invalid use of property

                                  Thanks baja_yu! Now everything works fine !

                                  P.S. I think my thread just broke a record («the fastest solved thread in vforums»).

                                  Last edited by Arispan; Jul 9th, 2010 at 08:23 AM.


                                • Home
                                • VBForums
                                • Visual Basic
                                • Visual Basic 6 and Earlier
                                • [RESOLVED] Compile error: Invalid use of property

                                Tags for this Thread


                                Posting Permissions

                                • You may not post new threads
                                • You may not post replies
                                • You may not post attachments
                                • You may not edit your posts
                                •  
                                • BB code is On
                                • Smilies are On
                                • [IMG] code is On
                                • [VIDEO] code is On
                                • HTML code is Off

                                Forum Rules


                                Click Here to Expand Forum to Full Width

                                Я пишу свой первый макрос MS Word, который перебирает все строки таблицы и удаляет выбранную. Вот код

                                Sub TableCleaner()
                                '
                                ' TableCleaner Macro
                                '
                                '
                                    Dim objTable As Table
                                    Dim sourceDocument As Document
                                    Set sourceDocument = ActiveDocument
                                    Dim UserChoice As String
                                    Dim QuestionToMessageBox As String
                                    QuestionToMessageBox = "Delete row with Text?"
                                
                                    Dim targetRows() As Row
                                    ReDim targetRows(1 To 1) As Row
                                    For Each oRow In sourceDocument.Tables(1).Rows
                                        UserChoice = MsgBox(oRow.Cells(1).Range.Text, vbYesNo, "Delete Row?")
                                        If UserChoice = vbYes Then
                                            targetRows(UBound(targetRows)) = oRow
                                            ReDim Preserve targetRows(1 To UBound(targetRows) + 1) As Row
                                            oRow.Shading.BackgroundPatternColor = Word.WdColor.wdColorLightGreen
                                        End If
                                    Next oRow
                                
                                    Confirmation = MsgBox("Are you sure?", vbYesNo, "Confirm?")
                                    If Confirmation = vbYes Then
                                        For Each targetRow In targetRows
                                            targetRow.Delete
                                        Next targetRow
                                    End If
                                
                                End Sub
                                

                                Я слежу за ошибкой в строке targetRows(UBound(targetRows)) = oRow

                                Compile error:
                                Invalid use of property
                                

                                3 ответа

                                Лучший ответ

                                Вам нужно Set целевой строки:

                                Set targetRows(UBound(targetRows)) = oRow
                                


                                0

                                drec4s
                                23 Мар 2018 в 18:58

                                Это потому, что Row является объектом, а не строкой, числом или чем-то «простым».

                                При назначении объекта вам нужно использовать ключевое слово Set. (Случается со мной все время в подобных ситуациях!) Итак:

                                Set targetRows(UBound(targetRows)) = oRow
                                

                                Примечание: вы должны использовать Option Explicit вверху ваших модулей кода. Это заставляет вас объявлять (использовать Dim) каждую переменную, которую вы используете, и помогает избежать орфографических ошибок с именами переменных и т. Д.


                                1

                                Cindy Meister
                                23 Мар 2018 в 18:58

                                В вашем коде, в строке ниже, он ожидает значение индекса как 1, 2, 3 для targetRows

                                TargetRows ( UBound (targetRows) ) = oRow


                                -1

                                jd_
                                23 Мар 2018 в 18:08

                                0 0 голоса
                                Рейтинг статьи
                                Подписаться
                                Уведомить о
                                guest

                                0 комментариев
                                Старые
                                Новые Популярные
                                Межтекстовые Отзывы
                                Посмотреть все комментарии

                                А вот еще интересные материалы:

                              • Яшка сломя голову остановился исправьте ошибки
                              • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
                              • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
                              • Invalid thread access ошибка фсс
                              • Invalid syntax python ошибка что означает