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?
asked Feb 1, 2014 at 20:06
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
3,4501 gold badge14 silver badges31 bronze badges
answered Feb 1, 2014 at 20:07
![]()
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
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
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
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
|
|
|
|
Популярные разделы FAQ:
Общие вопросы
Особенности VBA-кода
Оптимизация VBA-кода
Полезные ссылки
1. Старайтесь при создании темы указывать в заголовке или теле сообщения название офисного приложения и (желательно при работе с Office 95/97/2000) его версию. Это значительно сократит количество промежуточных вопросов.
2. Формулируйте вопросы как можно конкретнее, вспоминая (хотя бы иногда) о правилах ВЕЛИКОГО И МОГУЧЕГО РУССКОГО ЯЗЫКА, и не забывая, что краткость — сестра таланта.
3. Не забывайте использовать теги [сode=vba] …текст программы… [/code] для выделения текста программы подсветкой!
4. Темы с просьбой выполнить какую-либо работу полностью за автора здесь не обсуждаются и переносятся в раздел ПОМОЩЬ СТУДЕНТАМ.

В чем ошибка?
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
|
|
Full Member
Рейтинг (т): 5 |
Программа открывает файл, считывает один за другим параграфы и заполняет с помощью процедуры FillVisitUserWithLogData некую структурку visitUser полученными данными.
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 |
|
|
Full Member
Рейтинг (т): 18 |
а что имелось ввиду под этим: Set rngLogFileRange = parLogFile.Range.Select? п.с. на будующее юзай пошаговый запуск (F8) со включенными locals window (там отображаются значения всех переменных в данный момент) и watches window при необходимости (туда можно вставить дополнительные конструкции и отслеживать их значение)… Сообщение отредактировано: Krasnaja Shapka — 28.03.07, 06:31 |
|
awax |
|
|
Full Member
Рейтинг (т): 5 |
Цитата а что имелось ввиду под этим: Set rngLogFileRange = parLogFile.Range.Select?
При помощи Set rngLogFileRange = parLogFile.Range.Select я хотел установить рандж в 1 параграф, ну и передавать его процедуре для обработке. А Select для того, чтобы весь этот процесс наблюдать визуально, для контроля (где-то вычитал про такой прием). |
|
Krasnaja Shapka |
|
|
Full Member
Рейтинг (т): 18 |
разбей это на два оператора… Set rngLogFileRange = parLogFile.Range Добавлено 28.03.07, 09:33 FillVisitUserWithLogData parLogFile.Range, visitUser и избавишься от лишней переменной… Сообщение отредактировано: Krasnaja Shapka — 28.03.07, 09:34 |
|
awax |
|
|
Full Member
Рейтинг (т): 5 |
Цитата разбей это на два оператора… Set rngLogFileRange = parLogFile.Range Не-а, твой вариант тоже не работает. Кажется я нашел причину ошибки. Переменная rngLogFileRange объявляется вместе с еще одной:
Dim rngLogFileRange, rngRange As Range А если их объявить так:
Dim rngLogFileRange As Range Dim rngRange As Range то все работает правильно. Объяснения у меня этому нет. P.S.
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 |
|
|
Junior
Рейтинг (т): 9 |
В VBA, в отличие от VB, тип переменной нужно указывать после ее объявлеия. |
|
Krasnaja Shapka |
|
|
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 |
|
|
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!!!) при объявлении
Dim rngLogFileRange, rngRange As Range переменная rngLogFileRange объявляется как variant. В моем случае это недопустимо. |
|
pvr |
|
|
Junior
Рейтинг (т): 9 |
Цитата Цитата (pvr @ Вчера, 17:04) Это как? Table Function InsertNextOutputTable? Как в сях? Надо юзать Help или учебник какой….
Private Function InsertNextOutputTable(docDocument As Document, intTableIndex As Integer) As Table |
|
awax |
|
|
Full Member
Рейтинг (т): 5 |
Спасибо, pvr, но компилятор подкинул новую задачку. Функция InsertNextOutputTable создает таблицу и возвращает ссылку на нее.
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 Используется ф-я следующим образом:
Dim tblTargetTable As table ‘ … ‘ … ‘ … Set tblTargetTable = InsertNextOutputTable(docDocument:=docActive, intTableIndex:=visitUser.intIndex)
Во время прогона макроса, при входе в функцию, компилятор сразу останавливает выполнение программы, подсвечивает InsertNextOutputTable в последнем выражении функции и выдает ошибку Compile error: Invalid use of property. Все типы определены и совпадают. В чем дело? Учебник по VBA ответа на этот вопрос не дает |
Old Bat |
|
|
Moderator
Рейтинг (т): 128 |
Set InsertNextOutputTable = tblTable , но лучше сразу
Set InsertNextOutputTable = docDocument.Tables.Add(Range:=rngTable, NumRows:=1, NumColumns:=5) Цитата awax @ 30.03.07, 07:03 Учебник по VBA ответа на этот вопрос не дает
|
|
awax |
|
|
Full Member
Рейтинг (т): 5 |
Цитата что за источник ??
VBA for Dummies |
Old Bat |
|
|
Moderator
Рейтинг (т): 128 |
гм, попользуй ссылочку, много чего полезного есть |
|
awax |
|
|
Full Member
Рейтинг (т): 5 |
Цитата Old Bat @ 30.03.07, 10:57
Set InsertNextOutputTable = tblTable , но лучше сразу
Set InsertNextOutputTable = docDocument.Tables.Add(Range:=rngTable, NumRows:=1, NumColumns:=5)
Спасибо за подсказку. Все работает. Ссылку почитаю. Держи плюс |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- VB for Application
- Следующая тема
[ Script execution time: 0,0498 ] [ 16 queries used ] [ Generated: 28.01.23, 21:07 GMT ]
Tags for this Thread
|
|
Я пишу свой первый макрос 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







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




