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,5201 gold badge15 silver badges31 bronze badges

answered Feb 1, 2014 at 20:07

Dmitry Pavliv's user avatar

Dmitry PavlivDmitry Pavliv

35.4k13 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).

this has definitely been asked for but I’m not sure how the answers were applicable to my problem and so it remains unresolved. I’m looking to call certain codes when I click on a certain spreadsheet and have been able to do it until I included a fourth, new code. Now when I click on Sheet 2, the sheet with the code below, it highlights Sub Worksheet_Activate() and displays Invalid Use of Property.

Sub Worksheet_Activate()

Call VBAProject.Module1.ComplexCopyPust
Call VBAProject.Module2.ComplexCopyPust
Call SetPrintArea
Call Sort

End Sub

I only added the Call Sort. It worked with all the other codes beforehand.

Call Sort code below. I used record macro to create it.

Sub Sort()
'
' SortNumberLetter Macro
'

 On Error Resume Next
 'Finds last row of content
  ALastFundRow = Columns("C").Find("*", SearchDirection:=xlPrevious, 
  SearchOrder:=xlByRows, LookIn:=xlValues).Row


  '
On Error Resume Next
Range("A8:Q" & ALastFundRow).Select
ActiveWindow.SmallScroll Down:=-462
ActiveWorkbook.Worksheets("WIRE SCHEDULE").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("WIRE SCHEDULE").Sort.SortFields.Add Key:=Range( _
    "A8:A" & ALastFundRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortTextAsNumbers
ActiveWorkbook.Worksheets("WIRE SCHEDULE").Sort.SortFields.Add Key:=Range( _
    "C8:C" & ALastFundRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("WIRE SCHEDULE").Sort
    .SetRange Range("A8:Q" & ALastFundRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
End Sub

Anything helps!

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

Введение

Microsoft Visual Basic для приложений (VBA) — мощный инструмент для разработки макросов и приложений в Microsoft Office. Однако, при написании кода на VBA можно столкнуться с ошибкой «Invalid use of property», которая указывает на нехватку опыта в работе со свойствами.

Свойства в VBA

Свойство — это значение, которое может быть присвоено объекту в VBA. К примеру, вы можете задать ширину ячейки в Microsoft Excel, используя свойство «Width» объекта «Range».

Ошибка «Invalid use of property»

Ошибка «Invalid use of property» возникает, когда VBA не может правильно определить класс свойства или когда используется свойство, которое невозможно изменить. Эта ошибка может возникать по разным причинам, в том числе из-за неправильного синтаксиса или неправильно указанного типа свойства.

Правильное использование свойств

Для избежания ошибки «Invalid use of property» необходимо правильно использовать свойства в коде. Ниже приведены некоторые рекомендации для работы со свойствами в VBA:

1. Объявление переменных

Переменные должны быть объявлены с использованием соответствующего типа данных. К примеру, если вы используете свойство «Value» для объекта «Range», переменная должна быть объявлена как «Variant» или «Double».

2. Использование «Set»

Если вы используете свойство для присвоения значения объекту, то вы должны использовать «Set». К примеру:

Set myRange = Worksheets("Sheet1").Range("A1:B2")

3. Использование синтаксиса свойства

Для доступа к свойству объекта используйте синтаксис:

ObjectName.PropertyName

4. Проверка типа данных

Перед использованием свойства необходимо проверить тип данных. К примеру, если вы используете свойство «Value» для объекта «Range», вы должны проверить, является ли это значение числом.

Заключение

Использование свойств в VBA происходит в основном в процессе работы с объектами. Для избежания ошибки «Invalid use of property» необходимо правильно использовать свойства и следовать основным правилам программирования на VBA.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Iphone сбой проверки произошла неизвестная ошибка
  • Invalid thread access ошибка фсс
  • Invalid syntax renpy ошибка
  • Invalid syntax python ошибка что это
  • Invalid syntax python ошибка как исправить

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: