Maxim39 Пользователь Сообщений: 47 |
#1 17.09.2015 02:04:57 Доброй ночи всем! В модуле листа условие, если ячейка O7=BACK, то запустить макрос
В стандартном модуле должен после этого запуститься макрос Back. Инфу брал из:
Во вложении скрин ошибки и сама книга. Внимательно (!) она без программы, из которой по DDE получает инфу будет выдавать ошибки.
Прикрепленные файлы
Изменено: Maxim39 — 17.09.2015 11:20:12 |
||||
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
Maxim39, здравия. Во-первых, код следует оформлять соответствующим тэгом. (кнопка на панели инструментов области текста сообщения <…>) Изменено: JayBhagavan — 17.09.2015 02:15:57 <#0> |
Maxim39 Пользователь Сообщений: 47 |
#3 17.09.2015 02:21:50 Доброй ночи, JayBhagavan ! Ссори, в VBA слаб… не понял про теги. Такой код тоже вызывает ошибку:
Изменено: Maxim39 — 17.09.2015 13:39:11 |
||
TSN Пользователь Сообщений: 217 |
Процедура Back принимает четыре аргумента указанные в скобках после названия (channel as string, selection as string ….). Back без передачи аргументов, что неприемлемо. Что касается тегов VBA не причем. В момент когда создаете сообщение на форуме и хотите вставить код, часть кода нужно нажать Кнопка форматирования кода <…> после чего вставить код в форму с серым фоном. Изменено: TSN — 17.09.2015 08:45:38 |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#5 17.09.2015 10:00:47
VBA тут ни причём )) Ищите такую кнопку (см. скрин) для оформления кода. Прикрепленные файлы
|
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#6 17.09.2015 11:16:46 Предположу, что Back — это просто текст в ячейке и задача сравнить значение ячейки и если значение в ячейке Back, то вызвать эту процедуру
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Maxim39 Пользователь Сообщений: 47 |
#7 17.09.2015 14:08:52 TSN
, Юрий М — с тегом поправил, спасибо! The_Prist — да, верно Back — это просто текст. Увы тоже выдает ошибку, Excel сам выделяет Target, может в этом подсказка!?
Когда условие срабатывает (в ячейке O7 слово BACK), она вызывает Back там так и прописано, вписал как Вы написали, тоже ошибка. Прикрепленные файлы
|
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Target.Value = «BACK» Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Поменяйте или контрольное слово или имя вызываемого макроса, чтобы не было путаницы ) |
Maxim39 Пользователь Сообщений: 47 |
#10 17.09.2015 14:34:51
Спасибо, что помогаете!
Можно поменять кодовое слово на на анг B, ошибка не из-за этого… Изменено: Maxim39 — 17.09.2015 15:11:58 |
||||||
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#11 17.09.2015 14:44:57
Я не про ошибку — про путаницу )) |
||
Sclif666 Пользователь Сообщений: 720 |
Уже говорилось, что Sub Back требует параметров. |
Maxim39 Пользователь Сообщений: 47 |
#13 17.09.2015 14:52:46
Что значит требует параметров? Можно самый простой пример |
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Короче приложите свой файл и проблемы уйдут. Вы чего-то там наляпали, не знаете сами чего. Видимо ни процедур, ни других нужных вещей в проекте нет. Вот ошибки и лезут одна за другой. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Maxim39 Пользователь Сообщений: 47 |
Файл приложил сразу в первом посте, только внимательно, перед этим другие рабочие книги закрыть и заодно отключить макросы, т.к. книга будет ссылаться на программу которая у Вас не запущена и будет выдавать ошибки! |
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#16 17.09.2015 15:14:32 Тогда не буду скачивать. Зачем ковырять проект, который заведомо содержит неисправляемые ошибки. Если Ваша процедура BACK записана вроде:
значит она с аргументами. Т.е. если внутри скобок что-то написано и там есть хоть один As без Optional(Optional sArg as string) — значит надо в эту функцию/процедуру передать этот sArg:
Совет такой: потратьте пару часиков на чтение о передаче аргументов в функцию. Да и вообще об азах VBA. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Sclif666 Пользователь Сообщений: 720 |
#17 17.09.2015 15:16:00
|
||
Maxim39 Пользователь Сообщений: 47 |
The_Prist
, спасибо Вам за помощь и потраченное время, заходил на Ваш сайт, понимаю что занимаетесь сложными проектами и обучение начинающих не в приоритете. Книги скачал, но многое не понятно… буду дальше изучать. Sclif666 , спасибо за хороший пример, что-то я ступил с несколькими End Sub, буду дальше пробовать. Спасибо всем за подсказки, постараюсь разобраться! Если проблему решу — отпишусь здесь. Изменено: Maxim39 — 17.09.2015 15:47:27 |
Maxim39 Пользователь Сообщений: 47 |
#19 18.09.2015 01:06:00 Sclif666
, огромное СПАСИБО,только сейчас понял свою ошибку, сделал как Вы написали и всё заработало как надо! (см.скриншот) Прикрепленные файлы
|
I’m trying to figure this out and can’t.
I keep getting an error: «Compile error — Argument not optional». I am supplying the arguments and they are set as Optional!
Trying to pass a string and an array to a function and count occurrences of the array strings within the string passed.
Code stops running at the line:
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
with a «Compile error: Argument not optional» message highlighting the Val
in the line:
For Each Val In toCountARR
Full code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim nameR As Range
Dim colR As Range
Dim TKRcnt As Integer
Dim TKRarr() As Variant
TKRarr = Array("TKR", "THR", "Bipolar")
Dim ORIFcnt As Integer
Dim ORIFarr() As Variant
TKRarr = Array("ORIF", "Ilizarov", "PFN")
Set nameR = Range("P2:P9")
Set colR = Range("B2:B50,G2:G50,L2:L50")
For Each namecell In nameR
For Each entrycell In colR
If entrycell.text = namecell.text Then
TKRcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
ORIFcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
End If
Next entrycell
MsgBox (namecell.text & " TKR count: " & TKRcnt & " ORIF count: " & ORIFcnt)
Next namecell
End Sub
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
Dim cnt As Integer
Dim inStrLoc As Integer
For Each Val In toCountARR
inStrLoc = InStr(1, text, Val)
While inStrLoc <> 0
inStrLoc = InStr(inStrLoc, text, Val)
cnt = cnt + 1
Wend
Next Val
Set countTextInText = cnt
End Function
Before we dive into the solution for the error above, let us go back to basics to make sure you understand what a function is. This will be important for fixing and troubleshooting the error. Feel free to skip ahead if you have a good grasp of this concept already.
What is a function?
A block of code that is reusable can be called a “function.” The word “reusable” tells us that the function can be called any number of times and from anywhere in the project.
If we need to make an enhancement or modification in any flow of action which is already encapsulated in a function, we only need to make the change in one place — the function. This will handle the change in flow wherever the function has been called.
The block of code with a function name that is called in several places is named the “Called Function” and the line of code that calls the function is the “Calling function.”
Arguments in a function
Let’s say you have some data that’s required for the block of code — the function — to programmatically run. This data can be input in the same line as the function name.
These inputs are called as “Arguments” or “Parameters” in programming. We can define the data type of the arguments along with the variable names when defining the function. However, this is not mandatory.
Based on the usage of the variable arguments in the code, the data type of the arguments can be assumed too.
Return value in a function
After running the block of code programmatically, there may be some information that the function wants to pass back to the calling function. This is called the return value. Optionally, the data type of the return value can also be mentioned while defining the function.
Defining a function with arguments and a return value
Function
Let’s imagine a function called from a sub procedure of a save button on a student admission form. Let us name the function fn_SaveStudent
. The function will take all the field values from the form GUI and insert them as a student record into a database.
Arguments
The field values need to be sent as arguments from the calling function to the called function.
Return Value
In turn, the database will generate a “Student ID” automatically. The function can return this value to the calling function, which in turn can display the “Student ID” on any field in the student admission form” or in a message box.
Syntax of a function
Function <Function’s name> ([arg1 [, arg2 [, arg3 [ …… ] ] ] ] ])
<function code>
End Function
Where “arg” represents an argument.
For Example:
'Sub – procedure for the click event of a save button Private Sub cmdSave_Click() strName = txtName.Value intAge = lstAge.Value strGen = lstgender.Value lngContact = txtcontact.Value Call fn_SaveStudent(strName, intAge, strGen, lngContact) End Sub Function fn_SaveStudent(strName As String, intAge As Integer, strGen As String, lngContact As Long) As String 'code to insert the variable values in the parameters into the DB and get back the generated Student Id fnSaveStudent = strstudentId End Function
Built-In Functions
These functions are the predefined blocks of code offered by programming languages for various purposes. In VBA, we have a wide range of built-in functions. Some examples are found below.
S.no | Function Name | Quick Description | Syntax |
1 | Split | Split a string using a character as a delimiter. An array of words is returned | SPLIT ( <expression> [,<delimiter>] [,<limit>] [,<compare>]) |
2 | Cdbl | Convert expression to a double data type | CDBL ( <expression> ) |
3 | chr | Returns a string (character value) that corresponds to te ascii value passed as a parameter. | chr ( <ascii value> ) |
4 | Mid | Returns the middle part of a string when starting position and length are provided | MID ( <string>, <start> [,<length>]) |
5 | Left | Returns the left portion of a string when length is specified | LEFT ( <string>, <length> ) |
6 | Right | Returns the right portion of a string when length is specified | RIGHT ( <string>, <length> ) |
7 | Trim | Trim the leading and trailing spaced of a string | Trim ( <string> ) |
8 | Ucase | Converts all characters of the string to Upper case | Ucase ( <string> ) |
9 | Lcase | Converts all characters of the string to Lower case | Lcase ( <string> ) |
10 | Instr | Checks if one string is a substring of another string. If yes, it returns the starting position or else it returns 0. | INSTR([<start>] ,<string1> ,<string2> [,<compare>]) |
11 | Now | Returns the current system date and time | now() |
12 | Cstr | Converts the passed parameter value to a string | cstr ( <expression> ) |
13 | Val | Provides the mathematical value of the parameter. | value ( <expression> ) |
14 | Ltrim | Removes the leading spaces of the string and returns it. | Ltrim ( <string> ) |
15 | Rtrim | Removes the trailing spaces of the string and returns it. | Rtrim ( <string> ) |
16 | Date | Returns the current system date | date ( <expression> ) |
17 | Day | Returns the day from the date parameter passed. | Day (<a date in the yyyy,mm,dd format>) |
18 | Sin | Returns the sin value | Sin ( < expression> ) |
19 | Tan | Returns the tangent value | Tan ( < expression> ) |
20 | Cot | Returns the Cotangent value | Cot ( < expression> ) |
21 | Log | Returns the log value | Log ( < expression> ) |
22 | Cos | Returns the cos value | Cos ( < expression> ) |
23 | Isnull | Returns a boolean value depending on whether the parameter value is equivalent to “null” or not | Isnull ( <expression> ) |
24 | Isnumeric | Returns a boolean value depending on whether the parameter value is equivalent to a numeric value or not | Isnumeric ( <expression> ) |
25 | Rate | Returns a value of double data type as the interest rate for a series of equal cash flows at regular intervals. | RATE( <number_payments>, <payment>, <PV>, [<FV>], [<Type>], [<Estimate>] ) |
26 | Cint | Comvert the parameter value to an integer value | cint ( <expression> ) |
27 | Mkdir | Make the directory i.e. create a folder | mkdir ( <path_name> ) |
28 | Cvar | Convert the paramter value to a value of variant data type | CVAR(expression) |
29 | Ccur | Convert the paramter value to a value of currency data type | ccur ( <path_name> ) |
30 | cdate | Convert the paramter value to a date | cdate ( <path_name> ) |
Optional arguments & the error “Argument not optional”
User-defined functions
For user-defined functions, the arguments are considered optional or mandatory depending on whether you used the “OPTIONAL” keyword when defining the parameters in the called function.
Example
In this called function, no argument is defined with the “Optional” keyword, so when an argument is not passed in the calling function, we see the error message “Argument not Optional.”
In order to resolve this, we need to either pass the parameter in the calling function or mark the rollno argument as optional. The below piece of code fixes the error.
Sub demo1() Call fn_demo1("Baby Aneesh", "A+") End Sub Function fn_demo1(strname, strgrade, Optional ByVal introllno As Integer) 'Just display the values of all parameters MsgBox "Student name: " &amp;amp; strname &amp;amp; vbCrLf &amp;amp; "Grade: " &amp;amp; strgrade &amp;amp; vbCrLf &amp;amp; "Roll no: " &amp;amp; introllno End Function
Built-in Functions
In the case of built-in functions, the syntax clearly states whether the parameters are optional or mandatory.
Example
Syntax of Split Function from the table above:
SPLIT ( <expression> [,<delimiter>] [,<limit>] [,<compare>])
Here only the expression i.e. the string is a mandatory argument. So, the code runs successfully even if the last two optional arguments are not passed.
However if the mandatory argument is not passed, it results in the compile error “Argument not optional”.
To resolve this compile error, the mandatory arguments need to be passed to the function call.
Conclusion
The compile error discussed in this article is self-explanatory if you understand the purpose and usage of functions in general. We need to pass all mandatory arguments of the expected data type in order to avoid compile errors like this.
See also:
You’ve entered too many arguments for this function
- Remove From My Forums
-
Question
-
I have written a program, using VBA in Excel 2007, and it runs perfect. I have been reading that it is good practice to ‘compile’ your program, not something I have previously done. When I click compile, I get the following error: «Complie Error: Argument
not optional». What does this mean?The error occurs on this line of code: Call InsertVaRSummaryFigure
Which calls this function (which works fine):
Function InsertVaRSummaryFigure(SummarySheet As String)
Worksheets(SummarySheet).Select
strFindAddressClearSection = Range(«C1:C1000»).Find(«Total Core Rates GB», Range(«C1»), xlValues, xlWhole, xlByColumns, xlNext).Address
Range(strFindAddressClearSection).Offset(0, 2).Formula = «=-VaRData!D11»End Function
Can anyone enlighten me?
Answers
-
Hi Gazza101,
If you write this:
Function InsertVaRSummaryFigure(SummarySheet As String)
This means, that the parameter SummarySheet is not optional. You
must give that to the function.And if you write that:
Call InsertVaRSummaryFigure
you have no transfer parameter, so the compiler said: «Complie Error: Argument not optional»
You can try this:
Function InsertVaRSummaryFigure(Optional SummarySheet As String = "NameOfYourSheet")
or this:
Call InsertVaRSummaryFigure("NameOfYourSheet")
or both if you want a standard Sheet, or another different:
Function InsertVaRSummaryFigure(Optional SummarySheet As String = "Sheet1") Call InsertVaRSummaryFigure
or
Call InsertVaRSummaryFigure("SecondSheetInBla")
So, try
and have a look @ http://msdn.microsoft.com/en-us/library/f25e2b6b.aspx
Please ‘Mark as Answer’ if I helped. This helps others who have the same problem!
-
Marked as answer by
Wednesday, September 29, 2010 11:54 AM
-
Marked as answer by
I’m trying to figure this out and can’t.
I keep getting an error: «Compile error – Argument not optional». I am supplying the arguments and they are set as Optional!
Trying to pass a string and an array to a function and count occurrences of the array strings within the string passed.
Code stops running at the line:
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
with a «Compile error: Argument not optional» message highlighting the Val
in the line:
For Each Val In toCountARR
Full code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim nameR As Range
Dim colR As Range
Dim TKRcnt As Integer
Dim TKRarr() As Variant
TKRarr = Array("TKR", "THR", "Bipolar")
Dim ORIFcnt As Integer
Dim ORIFarr() As Variant
TKRarr = Array("ORIF", "Ilizarov", "PFN")
Set nameR = Range("P2:P9")
Set colR = Range("B2:B50,G2:G50,L2:L50")
For Each namecell In nameR
For Each entrycell In colR
If entrycell.text = namecell.text Then
TKRcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
ORIFcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr)
End If
Next entrycell
MsgBox (namecell.text & " TKR count: " & TKRcnt & " ORIF count: " & ORIFcnt)
Next namecell
End Sub
Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer
Dim cnt As Integer
Dim inStrLoc As Integer
For Each Val In toCountARR
inStrLoc = InStr(1, text, Val)
While inStrLoc <> 0
inStrLoc = InStr(inStrLoc, text, Val)
cnt = cnt + 1
Wend
Next Val
Set countTextInText = cnt
End Function