- 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
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 |
Юрий М Модератор Сообщений: 60383 Контакты см. в профиле |
#5 17.09.2015 10:00:47
VBA тут ни причём )) Ищите такую кнопку (см. скрин) для оформления кода. Прикрепленные файлы
|
||
The_Prist Пользователь Сообщений: 13995 Профессиональная разработка приложений для 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 Пользователь Сообщений: 13995 Профессиональная разработка приложений для MS Office |
Target.Value = «BACK» Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Юрий М Модератор Сообщений: 60383 Контакты см. в профиле |
Поменяйте или контрольное слово или имя вызываемого макроса, чтобы не было путаницы ) |
Maxim39 Пользователь Сообщений: 47 |
#10 17.09.2015 14:34:51
Спасибо, что помогаете!
Можно поменять кодовое слово на на анг B, ошибка не из-за этого… Изменено: Maxim39 — 17.09.2015 15:11:58 |
||||||
Юрий М Модератор Сообщений: 60383 Контакты см. в профиле |
#11 17.09.2015 14:44:57
Я не про ошибку — про путаницу )) |
||
Sclif666 Пользователь Сообщений: 696 |
Уже говорилось, что Sub Back требует параметров. |
Maxim39 Пользователь Сообщений: 47 |
#13 17.09.2015 14:52:46
Что значит требует параметров? Можно самый простой пример |
||
The_Prist Пользователь Сообщений: 13995 Профессиональная разработка приложений для MS Office |
Короче приложите свой файл и проблемы уйдут. Вы чего-то там наляпали, не знаете сами чего. Видимо ни процедур, ни других нужных вещей в проекте нет. Вот ошибки и лезут одна за другой. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Maxim39 Пользователь Сообщений: 47 |
Файл приложил сразу в первом посте, только внимательно, перед этим другие рабочие книги закрыть и заодно отключить макросы, т.к. книга будет ссылаться на программу которая у Вас не запущена и будет выдавать ошибки! |
The_Prist Пользователь Сообщений: 13995 Профессиональная разработка приложений для MS Office |
#16 17.09.2015 15:14:32 Тогда не буду скачивать. Зачем ковырять проект, который заведомо содержит неисправляемые ошибки. Если Ваша процедура BACK записана вроде:
значит она с аргументами. Т.е. если внутри скобок что-то написано и там есть хоть один As без Optional(Optional sArg as string) — значит надо в эту функцию/процедуру передать этот sArg:
Совет такой: потратьте пару часиков на чтение о передаче аргументов в функцию. Да и вообще об азах VBA. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Sclif666 Пользователь Сообщений: 696 |
#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.
Contents
- What is a function?
- Arguments in a function
- Return value in a function
- Defining a function with arguments and a return value
- Built-In Functions
- Optional arguments & the error “Argument not optional”
- User-defined functions
- Built-in Functions
- Conclusion
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
afasdfsadfs 0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
||||
1 |
||||
13.09.2020, 22:40. Показов 3118. Ответов 14 Метки нет (Все метки)
Здравствуйте ,дорогие форумчане ! Хотел передать несколько данных одному процедуру Sub Summ и выводит ошыбку , но когда я передаю одну переменную то все нормально . Не могли бы Вы объяснить в чем проблема ? Спасибо!
__________________
0 |
4037 / 1422 / 394 Регистрация: 07.08.2013 Сообщений: 3,539 |
|
13.09.2020, 23:14 |
2 |
у функции Summ1 три обязательных аргумента
0 |
0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
|
14.09.2020, 12:12 [ТС] |
3 |
snipe, но я же передаю ей 3 переменный . По одной из каждой процедуры Sub . А можно ли другим способом отправить 3 переменных из разных процедур в один, где произведется вычисление и выведет результат в определенную ячейку . Спасибо !
0 |
КостяФедореев Часто онлайн 774 / 522 / 233 Регистрация: 09.01.2017 Сообщений: 1,790 |
||||
14.09.2020, 12:24 |
4 |
|||
afasdfsadfs, в начале кода задайте переменные
и со скобок уберите переменные
0 |
4037 / 1422 / 394 Регистрация: 07.08.2013 Сообщений: 3,539 |
|
14.09.2020, 12:39 |
5 |
но я же передаю ей 3 переменный . По одной из каждой процедуры Sub . в том -то и дело что нужно не по одной передавать а все разом
Sub Summ1(Kol_vo As Single, Price As Single, proc_ckidki As Single) вот тут написано что нужно передавать именно одновременно а не по одной
0 |
0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
|
14.09.2020, 12:48 [ТС] |
6 |
КостяФедореев, Спасибо за ответ , задал переменные в начале кода, удалил со скобок Summ1 переменные. Теперь он выводит ошибку .Wrong number of arguments or invalid property assignment . Спасибо !
0 |
snipe 4037 / 1422 / 394 Регистрация: 07.08.2013 Сообщений: 3,539 |
||||
14.09.2020, 12:55 |
7 |
|||
должно быть так
0 |
Часто онлайн 774 / 522 / 233 Регистрация: 09.01.2017 Сообщений: 1,790 |
|
14.09.2020, 13:32 |
8 |
Теперь он выводит ошибку Вы покажите, что получилось по коду, Добавлено через 1 минуту
0 |
1781 / 1109 / 340 Регистрация: 11.07.2014 Сообщений: 3,924 |
|
14.09.2020, 14:00 |
9 |
afasdfsadfs, а лучше перед тем как писать программу набрать в поисковике ПРОЦЕДУРЫ и ФУНКЦИИ вба и чуточку почитать
0 |
afasdfsadfs 0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
||||
14.09.2020, 14:54 [ТС] |
10 |
|||
snipe,спасибо большое ,что помогает мне . Вот что у меня вышло . Но теперь он выводит ошибку в Sub proc_ckidki1(Kol_vo As Single) Сompile error : Argument not optional .Спасибо большое ,что помогает мне !!!
0 |
Часто онлайн 774 / 522 / 233 Регистрация: 09.01.2017 Сообщений: 1,790 |
|
14.09.2020, 15:03 |
11 |
Сообщение было отмечено afasdfsadfs как решение Решениеafasdfsadfs, так у Вас после 10 строки Kol_vo не задано Добавлено через 2 минуты
0 |
0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
|
14.09.2020, 16:02 [ТС] |
12 |
КостяФедореев, просто у меня есть несколько строчек которые я получаю через TextBox ,а для каждой из них создается отдельная процедура .Или есть возможность поместить их в одну процедуру . А как бы Вы сделали ? Спасибо !
0 |
3817 / 2245 / 750 Регистрация: 02.11.2012 Сообщений: 5,894 |
|
14.09.2020, 16:06 |
13 |
Сообщение было отмечено afasdfsadfs как решение Решениефайл приложить никак?
0 |
КостяФедореев Часто онлайн 774 / 522 / 233 Регистрация: 09.01.2017 Сообщений: 1,790 |
||||
14.09.2020, 16:41 |
14 |
|||
Сообщение было отмечено afasdfsadfs как решение Решениеafasdfsadfs, где находятся у Вас текстбоксы? Добавлено через 31 минуту
1 |
0 / 0 / 0 Регистрация: 05.05.2020 Сообщений: 186 |
|
14.09.2020, 17:16 [ТС] |
15 |
КостяФедореев, огромное спасибо Вам за помочь !!! Теперь я разобрался ,как нужно было это сделать . Еще раз ,СПАСИБО!!!
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
14.09.2020, 17:16 |
15 |
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Argument not optional (Error 449) |
vblr6.chm1011248 |
vblr6.chm1011248 |
office |
04d08e66-7084-8c94-52b1-b471423846ca |
06/08/2017 |
medium |
The number and types of arguments must match those expected. This error has the following causes and solutions:
-
Incorrect number of arguments. Supply all necessary arguments. For example, the Left function requires two arguments; the first representing the character string being operated on, and the second representing the number of characters to return from the left side of the string. Because neither argument is optional, both must be supplied.
-
Omitted argument isn’t optional. An argument can only be omitted from a call to a user-defined procedure if it was declared Optional in the procedure declaration. Either supply the argument in the call or declare the parameter Optional in the definition.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
-
#1
Hi people
I am using UerForms majorly for the first time, and I am having a bit of a mistifying problem…
The first userform takes and input and gives three choices: Exit, Use the Input, Manual Search.
Exit has the following code:
Code:
Private Sub BRefExit_Click()
Unload Me
End Sub
and that works fine, but the Manual Search button has this code:
Code:
Private Sub BRefSearch_Click()
Unload.me
Selecta.Show
End Sub
This is not so very different, but returns this error: Compile Error: Argument not Optional, and selects Unload.Me, then when I click ok, it highlights the top line. I tried silly things like this (which I probably should have guessed would not work):
Code:
Private Sub BRefSearch_Click()
If 1 = 1 Then
Unload.Me
Else
Unload Me
End If
Selecta.Show
End Sub
but nothing seems to correct it.
Why has Excel turned on me like this?
Thanks for reading this, and any answers gratefully received (particularly by my fast disintegrating teeth)
Mark
What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
-
#2
Code:
Private Sub BRefSearch_Click()
If 1 = 1 Then
Unload.Me
Else
Unload Me
End If
Selecta.Show
End Sub
If 1 = 1?
Well, 1 = 1 so it will unload unless you put something else into the equation…
Code:
If Range("A1") = "1" Then
Unload Me
Else
Unload Me
Userform2.Show
End If
Not sure, but I think the forms name «Selecta» is part of the problem. Try to renaming it and then use something like:
Code:
Sub But_Close()
Unload Me
NewName.Show
End Sub
Last edited: Sep 22, 2010
-
#3
This will unload the userform:
This will do nothing but crash your program:
It’s a surprise you hadn’t figured that out yet … The unload syntax is different than the usual. I remember being puzzled by it myself and posting a similar question about two years ago or so. As matter of technicalities, it seems the form is not unloaded by a method of its own (a «Me» method) but by a vba command. Something along those lines anyway.
Edit:
Just noticing in the last post attention to the SelectA.Show line … You may find that it crashes because you can’t (I don’t think) run command from an object you’ve just destroyed. So you may have more errors to deal with …
Last edited: Sep 22, 2010
-
#4
Oh my word… Thank you — well spotted! I am just off to bed, and I can sleep easy now I know that I have been an idiot again, and Excel is not out to get me (a scary prospect in anyone’s workbook).
Thanks a lot :¬D
apologies for wasting your time — that had got me totally stumped.
-
#5
This will do nothing but crash your program:
Completely missed Unload.Me, sorry.
That caused the first part of the problem:
Code:
If 1 = 1 Then
Unload.Me <-- here
Else
Unload Me <-- Here you got it right
<-- But since 1 = 1 you'll never got here
End If
Selecta.Show
End Sub
Edit:
Just noticing in the last post attention to the SelectA.Show line … You may find that it crashes because you can’t (I don’t think) run command from an object you’ve just destroyed. So you may have more errors to deal with …
Meaning this?
I use that a lot and it works fine for me. I assume that it reads all code til the end of the sub, or am I wrong?
-
#6
Meaning this?
Code:Unload Me
Userform2.ShowI use that a lot and it works fine for me. I assume that it reads all code til the end of the sub, or am I wrong?
Yes — but it sounds like my worry is unfounded — so it must be that the remaining code in the procedure does execute, before the form is actually destroyed. Good to know.
-
#7
Hello!
I learing HMI/SCADA iFIX. I made a user form. The problem occurs when i call user form named Modify.
Private Sub CommandButton3_Click()
Modify.Show
End Sub
After I click CommandButton3 program display me error. Compile error: Agrument not optional!
How to fix this error?
-
#8
I solved this issue. I just rename user form and it works.
-
05-07-2018, 06:43 AM
#1
Compile error argument not optional
I have a VBA in Excel that check Word files for a certain keyword and then should copy the table following the keyword to an Excel worksheet. Using input from other forums I had separate codes for both; searching the keyword and table, and copying the table to Excel. However I fail to combine the two. Everytime I get a compile error in the bold line that the ‘argument is not optional’ but I fail to see where an argument is missing. Stand alone both scripts work as expected. If anyone is able to spot what is wrong and how it can be solved, that would be much appreciated.
Sub ImpTable()Dim oWdApp As New Word.Application Dim oWdDoc As Word.Document Dim oWdTable As Word.Table Dim oWS As Worksheet Dim lLastRow$, lLastColumn$ With ThisWorkbook Set oWdDoc = oWdApp.Documents.Open("path") 'oWdDoc.Activate 'Application.ScreenUpdating = False Dim StrFnd As String, Rng As Range, i As Long StrFnd = "keyword" With ActiveDocument.Range With .Find .ClearFormatting .Replacement.ClearFormatting .Text = StrFnd .Replacement.Text = "" .Forward = True .Wrap = wdFindStop .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute End With Do While .Find.Found i = .Information(wdActiveEndAdjustedPageNumber) Set Rng = ActiveDocument.GoTo(What:=wdGoToPage, Name:=i) Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="page") If Rng.Tables.Count > 0 Then With Rng.Tables(1) Set oWdTable = Rng.Tables(1) oWdTable.Range.Copy oWS.Range("A1").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone End With Else MsgBox "no table." End If .Start = Rng.End .Find.Execute Loop End With 'Application.ScreenUpdating = True oWdDoc.Close savechanges:=False oWdApp.Quit End With End Sub
-
05-07-2018, 08:10 AM
#2
Show us the two Stand-Alone Codes.
I expect the student to do their homework and find all the errrors I leeve in.
-
05-07-2018, 08:10 AM
#3
I only dabble in Word VBA, but I’m fairly sure that is an illegal assignment. Your code defines ActiveDocument.Range as a Word range, while Rng is defined as an Excel range. The data types are not compatible. Perhaps if you redefined rng as a word range?
-
05-07-2018, 11:55 PM
#4
Originally Posted by SamT
Show us the two Stand-Alone Codes.
Here are the codes for respectively copying the Word table to Excel and analysing the Word file to find the table. I tried to combine these but this failed.
Sub CopyTableFromWordDoc(ByVal oFile As file)Dim oWdApp AsNew Word.Application ' Requires "Microsoft Word .. Object Library" reference Dim oWdDoc As Word.Document Dim oWdTable As Word.Table Dim oWS As Worksheet Dim lLastRow$, lLastColumn$ ' Code to copy table from word document to this workbook in a new worksheet With ThisWorkbook ' Set oWdTable ' Copy the table to new worksheet oWdTable.Range.Copy oWS.Range("A1").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone ' Close the Word document oWdDoc.Close False ' Close word app oWdApp.Quit EndWith EndSub
Thanks to Zac.
and in Word VBA;
Sub Demo()Application.ScreenUpdating =False Dim StrFnd AsString, Rng As Range, i AsLong StrFnd = "keyword" With ActiveDocument.Range With.Find .ClearFormatting .Replacement.ClearFormatting .Text = StrFnd .Replacement.Text ="" .Forward =True .Wrap = wdFindStop .Format =False .MatchCase =False .MatchWholeWord =False .MatchWildcards =False .MatchSoundsLike =False .MatchAllWordForms =False .Execute EndWith DoWhile.Find.Found i =.Information(wdActiveEndAdjustedPageNumber) Set Rng = ActiveDocument.GoTo(What:=wdGoToPage, Name:=i) Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="page") If Rng.Tables.Count >0Then With Rng.Tables(1) 'here the table should be copied to the Excel sheet EndWith Else MsgBox "No table." EndIf .Start = Rng.End .Find.Execute Loop EndWith Application.ScreenUpdating =TrueEndSub
Thanks to Macropod.
-
05-08-2018, 12:21 AM
#5
Originally Posted by rlv
I only dabble in Word VBA, but I’m fairly sure that is an illegal assignment. Your code defines ActiveDocument.Range as a Word range, while Rng is defined as an Excel range. The data types are not compatible. Perhaps if you redefined rng as a word range?
Dohh that makes perfect sense. I corrected that.
Last edited by plaem; 05-08-2018 at 01:12 AM.
-
05-08-2018, 02:01 AM
#6
So bit by bit I have combined codes to get my desired script. The goal is to analyze a folder of various Word files, extract a certain table from each Word file and paste it into a separate Excel worksheet which has the name of the doc file:
Sub LookForWordDocs()Dim FolderName As String With Application.FileDialog(msoFileDialogFolderPicker) .AllowMultiSelect = False .Show On Error Resume Next FolderName = .SelectedItems(1) Err.Clear On Error GoTo 0 End With Dim sFoldPath As String: sFoldPath = FolderName ' Change the path. Ensure that your have "" at the end of your path Dim oFSO As New FileSystemObject ' Requires "Microsoft Scripting Runtime" reference Dim oFile As File ' Loop to go through all files in specified folder For Each oFile In oFSO.GetFolder(sFoldPath).Files ' Check if file is a word document. (Also added a check to ensure that we don't pick up a temp Word file) If ((InStr(1, LCase(oFSO.GetExtensionName(oFile.Path)), "doc", vbTextCompare) > 0) Or _ (InStr(1, LCase(oFSO.GetExtensionName(oFile.Path)), "docx", vbTextCompare) > 0)) And _ (InStr(1, oFile.Name, "~$") = 0) And _ ((InStr(1, oFile.Name, "k") = 1) Or (InStr(1, oFile.Name, "K") = 1)) Then ' Call the UDF to copy from word document ImpTable oFile End If Next End Sub Sub ImpTable(ByVal oFile As File) Dim oWdApp As New Word.Application Dim oWdDoc As Word.Document Dim oWdTable As Word.Table Dim oWS As Excel.Worksheet Dim lLastRow$, lLastColumn$ Dim s As String s = "No correct table found" With ThisWorkbook Set oWS = Excel.Worksheets.Add On Error Resume Next oWS.Name = oFile.Name On Error GoTo 0 Set sht = oWS.Range("A1") Set oWdDoc = oWdApp.Documents.Open(oFile.Path) oWdDoc.Activate 'Application.ScreenUpdating = False Dim StrFnd As String, Rng As Word.Range, i As Long, j As Long StrFnd = "keyword" With Word.ActiveDocument.Range With .Find .ClearFormatting .Replacement.ClearFormatting .Text = StrFnd .Replacement.Text = "" .Forward = True .Wrap = wdFindStop .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute End With Do While .Find.Found i = .Information(wdActiveEndAdjustedPageNumber) Set Rng = ActiveDocument.Goto(What:=wdGoToPage, Name:=i) Set Rng = Rng.Goto(What:=wdGoToBookmark, Name:="page") If Rng.Tables.Count > 0 Then With Rng.Tables(1) Set oWdTable = Rng.Tables(1) oWdTable.Range.Copy sht.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone j = 1 End With End If .Start = Rng.End .Find.Execute Loop End With If j = 0 Then sht.Value = s 'Application.ScreenUpdating = True oWdDoc.Close savechanges:=False oWdApp.Quit End With Set oWS = Nothing Set sht = Nothing Set oWdDoc = Nothing Set oWdTable = Nothing Set Rng = Nothing End Sub
With Word.ActiveDocument.Range
The first table copies fine but then I get a “Run-time error 462 : The remote server machine does not exist or is unavailable” on line «With Word.ActiveDocument.Range». Any idea what may cause this and how it can be solved?Last edited by plaem; 05-08-2018 at 02:37 AM.
-
05-08-2018, 06:32 AM
#7
Option Explicit Sub test() Dim wd As Word.Application Dim StrFnd As String Dim r As Word.Range, rr As Word.Range, t As Word.Table Dim p As String, f As String Dim wb As Workbook Dim ws As Worksheet Dim n As Long Dim i As Long StrFnd = "keyword" With Application.FileDialog(msoFileDialogFolderPicker) .Title = "Plesse choose the folder" If Not .Show Then Exit Sub p = .SelectedItems(1) & "" End With Set wd = New Word.Application wd.Visible = True Set wb = Workbooks.Add(xlWBATWorksheet) f = Dir(p & "*.docx") Do While f <> "" With wd.Documents.Open(p & f) Set r = .Range With r.Find .Text = StrFnd Do While .Execute Set t = Nothing On Error Resume Next Set t = r.GoTo(What:=wdGoToBookmark, Name:="page").Tables(1) On Error GoTo 0 Application.Wait [Now() + "0:00:00.1"] If Not t Is Nothing Then If ws Is Nothing Then Set ws = wb.Worksheets.Add ws.Name = f End If t.Range.Copy ws.Range("a1").Offset(n).PasteSpecial xlPasteValues Application.CutCopyMode = False n = n + t.Rows.Count + 2 End If Loop End With .Close False Set ws = Nothing n = 0 End With f = Dir() Loop wd.Quit Set wd = Nothing End Sub
マナ
-
05-08-2018, 03:37 PM
#8
So bit by bit I have combined codes to get my desired script.
I try to break my code into many small Procedures, so I can Troubleshoot each one by itself. This also makes it easy to reuse Procedures
I expect the student to do their homework and find all the errrors I leeve in.