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,4901 gold badge14 silver badges31 bronze badges

answered Feb 1, 2014 at 20:07

Dmitry Pavliv's user avatar

Dmitry PavlivDmitry Pavliv

35.3k13 gold badges79 silver badges80 bronze badges

3

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. 

analyst

437 / 144 / 9

Регистрация: 12.01.2009

Сообщений: 678

Записей в блоге: 1

1

12.02.2010, 16:42. Показов 12033. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет! При использовании свойства path возникает ошибка:
Compile error: Invalid use of property

Visual Basic
1
2
3
Sub fen()
ThisWorkbook.Path
End Sub

Пример использования данной конструкции нашёл здесь:

В чем может быть ошибка (кроме отсутствия у меня мозгов)?



0



EducatedFool

0 / 0 / 0

Регистрация: 28.09.2009

Сообщений: 88

12.02.2010, 16:55

2

При использовании свойства path возникает ошибка

Что-то в вашем коде я не вижу использования этого свойства…

Использовать его надо хоть как-то, а то VBA получает значение этого свойства, а что с ним дальше делать — не знает…

Visual Basic
1
2
3
4
5
Sub fen()
    x = ThisWorkbook.Path
    'или
    MsgBox ThisWorkbook.Path
End Sub



0



437 / 144 / 9

Регистрация: 12.01.2009

Сообщений: 678

Записей в блоге: 1

12.02.2010, 16:59

 [ТС]

3

Цитата
Сообщение от EducatedFool
Посмотреть сообщение

Что-то в вашем коде я не вижу использования этого свойства…

Использовать его надо хоть как-то, а то VBA получает значение этого свойства, а что с ним дальше делать — не знает…


Спасибо!) Пора спать)



0



Вопрос:

Я знаю, что есть тонны нитей и вопросов об этом, и это довольно очевидно, как правило, где ошибка. Большинство людей не используют ключевое слово 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).

Понравилась статья? Поделить с друзьями:
  • Invalid syntax python ошибка while
  • Invalid syntax python ошибка print
  • Invalid subtitle file reaper ошибка
  • Invalid stored block lengths ошибка как исправить
  • Invalid start mode archive offset tlauncher ошибка