I’m new and trying to learn VBA. When I’m typing in the code I get Compile Error Expected Function Or Variable.
Is something regarding the activecell, but can’t figure it out.
Sub Testare()
Dim FilmName As String
Dim FilmLenght As Integer
Dim FilmDescription As String
Range("b10").Select
FilmName = ActiveCell.Value
FilmLenght = ActiveCell.Offset(0, 2).Value
If FilmLenght < 100 Then
FilmDescription = "Interesant"
Else
FilmDescription = "Suficient"
End If
MsgBox FilmName & " is " & FilmDescription
End Sub
Josh Crozier
228k54 gold badges386 silver badges301 bronze badges
asked Apr 24, 2014 at 16:41
3
This error happens also when a Sub is called the same as variable (i.e. in one Sub you have for loop with iterator «a», whilst another Sub is called «a»).
This gives an error that fits to your description.
Regards
answered Mar 10, 2015 at 17:22
Artur RutkowskiArtur Rutkowski
4374 gold badges9 silver badges16 bronze badges
It is possible to make your code fail in two different ways:
- Place a very large value in D10
- Place a text value in D10
This will result in either an overflow error or type mismatch error.
answered Apr 24, 2014 at 17:20
Gary’s StudentGary’s Student
94.9k9 gold badges58 silver badges97 bronze badges
I know this was asked a while ago, but I ended up with the same error when I created a Sub within a worksheet with the Sub Name the same as the Worksheet name.
Unfortunately when this happens, no error is highlighted by a compile; the error only appears at run time. Also, the offending line is not highlighted, which makes it a bit difficult to find.
Changing the Sub name solves it though.
Nippey
4,65835 silver badges44 bronze badges
answered Oct 23, 2014 at 11:47
Here is what caused this error in my case:
Inside a new Public Function that I was starting to write, I began to type a statement, but needed to copy a long varname from another location, so I just inserted the letter a
to prevent Excel from popping-up the uber-annoying Compile Error: Expected Expression
dialog. So I had this:
myVarName = a
I then attempted to step-through my code to get to that point, and when Excel entered that function I received the message "Compile Error: Expected Function Or Variable"
. To resolve, I just changed the placeholder to a number:
myVarName = 1
And all continued just fine.
answered Aug 7, 2018 at 16:22
cssyphuscssyphus
36.7k18 gold badges93 silver badges108 bronze badges
I recently had to edit somebody’s VBA macro in Excel for a recurrent data cleaning task. The code was a mess because large chunks of it were created using Excel’s macro recorded. While structuring the code in subroutines and modules, I ran into an error. In this blog post I would like to elaborate on it.
The code that I inherited contained a long list of poorly named modules with even poorer subroutines and functions inside it. I started restructuring the code base in something more understandable. Once I ran the macro, I was presented the following error.
Compile Error: Expected variable or procedure, not module
Apparently, the compiler expects a variable or procedure, but it received a module. Apparently, the solution is extremely simple: it is not exactly smart to give subroutines the same name as your modules.
VBA allows subroutines and function to have the same names, as long as they are declared in different modules. By preceding a subroutine in a call with its module, one can specify which subroutine needs to be evaluated.
Let’s say we have a module editValue and it contains a subroutine editValue.
Call editValue 'Produces an error Call editValue.editValue 'Works
The first line of code will fail because editValue is first evaluated as the module name, and modules cannot be called. The second line will work, because we specified the module explicitly, which ensures editValue is evaluated as a subroutine.
Happy scripting!
Say thanks, ask questions or give feedback
Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.
bazboy Пользователь Сообщений: 8 |
#1 27.08.2018 16:50:39 Добрый день, уважаемые форумчане! Прошу подсказать — написал такой макрос и привязал его к кнопке. При написании с отладкой проблем не было, режим был доступен. Просьба подсказать, в чем косяк.
Изменено: bazboy — 27.08.2018 20:53:39 |
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13995 Профессиональная разработка приложений для MS Office |
#2 27.08.2018 16:57:14 Вы хоть напишите в какой строке возникает ошибка. И что значит:
как Вы его пытаетесь сделать? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
bazboy Пользователь Сообщений: 8 |
#3 27.08.2018 17:04:39
указатель в код и F8 |
||
Допустим. А ошибка-то в какой строке? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
|
bazboy Пользователь Сообщений: 8 |
в том-то и дело, что ничего не подсвечивает |
ivanok_v2 Пользователь Сообщений: 712 |
#6 27.08.2018 17:37:29
Видиш суслика? Нет. |
||
Alemox Пользователь Сообщений: 2183 |
#7 27.08.2018 18:50:53 Если у вас в модуле стоит
у вас переменная не найдена, а код дальше продолжает своё действие, и далее упирается опять в ошибку когда выполняет строку
потому что ColumnN=0 Мастерство программиста не в том, чтобы писать программы, работающие без ошибок. |
||||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13995 Профессиональная разработка приложений для MS Office |
#8 27.08.2018 20:40:05
если почитать, то раньше как-то иначе отладку проводили, не по F8? В какой момент перестало работать?
переменная wrkBook будет Nothing и далее посыпят ошибки. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
bazboy Пользователь Сообщений: 8 |
#9 28.08.2018 16:05:40 Добрый день!
Именно))
Нет Option Explicit не стоял, спасибо — установил Require Variable Declaration в настройках.
Спасибо, поправил — теперь в случае невыполнения условия сразу к закрытию после сообщения.
так и проводил, после выходных перестало Дмитрий, понимаю, что с этого походу надо было начинать, но только сегодня осознал Изменено: bazboy — 28.08.2018 16:06:01 |
||||||||||
bazboy Пользователь Сообщений: 8 |
#10 28.08.2018 16:08:00
Проверил, нормально открываются — думаю, изначально были бы проблемы. Через кнопку макрос отрабатывает. |
||
Поместите код макроса из модуля листа в стандартный модуль. Тогда F8 будет работать. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
|
bazboy Пользователь Сообщений: 8 |
#12 28.08.2018 17:27:47 Дмитрий(The_Prist) Щербаков, оно! Спасибо! |
- Remove From My Forums
-
Question
-
I’m getting this odd error in my code. its probably obvious but i’ve been staring at it for so long i’ve got code blindness ! i’ve highlighted the error line in red below.
error is : expected function or variable
the msdn definition is here :http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msaa/msaaccrf_0bla.asp
Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, ByVal HWnd As Long, ByVal idObject As Long, ByVal idChild As Long, ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long
Dim ObA As IAccessible
Dim LRet As Long
Dim V As Variant
Dim s As String, s1 As String, sName As String
On Error Resume Next
Dim pxLeft As Long, pyTop As Long, pcxWidth As Long, pcyHeight As LongpxLeft = 0
pyTop = 0
pcxWidth = 0
pcyHeight = 0‘Select Case LEvent
‘Case SYS_FOREGROUND, SYS_ALERT, OB_FOCUS, OB_SELECTION, OB_VALUECHANGE
LRet = AccessibleObjectFromEvent(HWnd, idObject, idChild, ObA, V)
If LRet = 0 Then
With F1
sName = ObA.accName(V)
.Text1(0).Text = sName .Text1(1).Text = ObA.accDescription(V)
s1 = ObA.accValue(V)
.Text1(2).Text = s1
.Text1(3).Text = ObA.accRole(V)
.Text1(4).Text = ObA.accState(V)RECT = ObA.accLocation(pxleft, pytop, pcxwidth, pcyheight, V)
End WithIf (ObA.accState(V) And STATE_UNAVAILABLE) Then
s = » disabled»
End IfIf LEvent = OB_VALUECHANGE Then
s = s1 & s
Else
s = sName & sEnd If
End If
WinEventFunc = 0
End Function
Answers
-
You have this at the bottom:
End Function
End Sub
is that a typo?
-
If the problem is on the line you’ve highlighted, then i would make sure that the ObA object has a function called accLocation()
Also, where is RECT being defined? I don’t see it in this function.
RECT is also commonly used as a object name. You may want to consider calling it something else.
Содержание
- Compile error expected function or variable
- Answered by:
- Question
- Compile error expected function or variable
- Answered by:
- Question
- Compile Error:- expected function or variable problem
- Compile Error:- expected function or variable problem
- Re: Why is this Macro not working?
- Re: Why is this Macro not working?
- Re: Macro — Code Problem?
- Re: Macro — Code Problem?
- Re: Macro — Code Problem?
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Re: Compile Error:- expected function or variable problem
- Compile error expected function or variable
- Лучший отвечающий
- Вопрос
- Thread: VBA module call in userform to diff sheets error: «expected function or variable»
- VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
- Re: VBA module call in userform to diff sheets error: «expected function or variable»
Compile error expected function or variable
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I’m getting this odd error in my code. its probably obvious but i’ve been staring at it for so long i’ve got code blindness ! i’ve highlighted the error line in red below.
error is : expected function or variable
the msdn definition is here :http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msaa/msaaccrf_0bla.asp
Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, ByVal HWnd As Long, ByVal idObject As Long, ByVal idChild As Long, ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long
Dim ObA As IAccessible
Dim LRet As Long
Dim V As Variant
Dim s As String, s1 As String, sName As String
On Error Resume Next
Dim pxLeft As Long, pyTop As Long, pcxWidth As Long, pcyHeight As Long
pxLeft = 0
pyTop = 0
pcxWidth = 0
pcyHeight = 0
‘Select Case LEvent
‘Case SYS_FOREGROUND, SYS_ALERT, OB_FOCUS, OB_SELECTION, OB_VALUECHANGE
LRet = AccessibleObjectFromEvent(HWnd, idObject, idChild, ObA, V)
If LRet = 0 Then
With F1
sName = ObA.accName(V)
.Text1(0).Text = sName .Text1(1).Text = ObA.accDescription(V)
s1 = ObA.accValue(V)
.Text1(2).Text = s1
.Text1(3).Text = ObA.accRole(V)
.Text1(4).Text = ObA.accState(V)
RECT = ObA.accLocation(pxleft, pytop, pcxwidth, pcyheight, V)
End With
If (ObA.accState(V) And STATE_UNAVAILABLE) Then
s = » disabled»
End If
If LEvent = OB_VALUECHANGE Then
s = s1 & s
Else
s = sName & s
Источник
Compile error expected function or variable
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Hi,
Im new to this forum and VBA but have experience in many other languages.
I have a form with the following fields: Week, Day, Work_Order, Operator, Reading_Number, Disc_Size, USL, LSL, Centre, Outer_Position_1, Outer_Position_2, Outer_Position_3, Outer_Position_4, Outer_Average.
I want the SQL code to get the last Reading_Number of a certain Disc_Size when the Disc_Size field is changed.
eg The last Reading_Number of a Disc_Size 2 is 33
The Disc_Size field is changed from 1.6 to 2 so now the value 34 will be automatically entered into the Reading_Number field.
I’ve think I’ve attached a picture of the form and below is the code I’m trying to use.
I’m getting the following error at Private Sub Disc_Size_Change() :
«Compile error: Expected function or variable»
Thanks, I hope I was clear? I have other VBA code that runs under certain conditions which I can post if it might be involved.
Источник
Compile Error:- expected function or variable problem
LinkBack
Thread Tools
Rate This Thread
Display
Compile Error:- expected function or variable problem
A Code Problem — In Microsoft Visual Basic, I’m getting this message,
Compile Error:- expected function or variable
What’s Wrong?
The Sub Hide_Protect() is highlighted in Yellow.
Cells.Select — Cells. is hightlighted in Blue.
Last edited by skin.uk1; 07-08-2011 at 01:12 PM .
Re: Why is this Macro not working?
Hi skin.uk1, before anyone can help you, you must amend your title as per Rule #1 and also wrap your code in code tags as per Rule #3 in the forum rules located here.
If you’re happy with someone’s help, click that little star at the bottom left of their post to give them Reps.
—Keep on Coding in the Free World—
Re: Why is this Macro not working?
Hi
I have amended it, Can anyone help me, I’m stuck?
Re: Macro — Code Problem?
Hi skin.uk1, you haven’t used code tags around your code as per rule 3. We are not aloud to help unless all the rules are followed. Sorry, but even those that help are chastised by mods if the thread doesn’t follow forum rules.
Re: Macro — Code Problem?
Sorry, I am new to all this!
Can you help me now please, I really need help.
Re: Macro — Code Problem?
Is this title more accurately to my problem under rule 1.
If not please help?
Re: Compile Error:- expected function or variable problem
I changed the title using your own words —
Re: Compile Error:- expected function or variable problem
Thank you,
Can you please help me now, I really need help because I’m stuck and can not move forwards with help.
Re: Compile Error:- expected function or variable problem
Hi skin.uk1, I don’t get any errors with your code. However, I don’t know what it is you are trying to do. Perhaps you could upload a mock workbook with mockdata, as well as provide before and after scenarios with your data.
Re: Compile Error:- expected function or variable problem
I have uploaded a mockup! I have manually done the coding up to 13th!
Last edited by skin.uk1; 07-08-2011 at 01:19 PM .
Re: Compile Error:- expected function or variable problem
Thanks for the upload skin.uk1 but what do you want done? All the sheets look the same, even after sheet 13. As far as your code goes, all it seems to be doing is selecting and activating ranges and nothing else.
Re: Compile Error:- expected function or variable problem
I want to record a Macro to make life and time easier. I have done 1st — 12th Manually.
This is what I have done.
Click on Record a Macro.
Macro name:- Hide_Protect
CTRL +h
Click on top left of the screen to highlight the whole sheet.
Right click — format cells, Protection tab, untick locked.
I Highlight using CTRL & the mouse on the following cells,
B9, C9, G9, H9,
H18, H30:H62,
H66:H98, C98:G98.
I still hold down CTRL, right click, format cells, Protection tab, tick — Locked & Hidden.
I go to Tools, Protection, protect sheet, enter password twice. ok
When I try to run the Macro (CTRL+h) on 14th,
Microsoft Visual Basic pops up,
with a box saying — Compile error:- expected function or Variable.
The coding is at top of page.
Help, what have i done wrong.
Re: Compile Error:- expected function or variable problem
Give the following code a try instead. It will loop through each sheet for you, unlock all cells, lock only the cells you specified, and then protect the sheet with a password (just change the password to desired»)
Notes about the macro:
May give an error if any of the sheets are already protected.
Hope that helps,
Re: Compile Error:- expected function or variable problem
FYI, your error is due to you having a sub in the other module called Cells. Since Cells is a built-in Excel property, that’s not a good name — if you rename that sub (e.g. mycells) then your code works, though it is not efficient (all that scrollrow stuff is unnecessary but the macro recorder generally records all the steps you take in Excel including just moving around the worksheet)
I would suggest you use Tigeravatar’s code instead.
Welcome to the forum, by the way, and thank you for amending your post as requested.
Источник
Compile error expected function or variable
Лучший отвечающий
Вопрос
I’m getting this odd error in my code. its probably obvious but i’ve been staring at it for so long i’ve got code blindness ! i’ve highlighted the error line in red below.
error is : expected function or variable
the msdn definition is here :http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msaa/msaaccrf_0bla.asp
Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, ByVal HWnd As Long, ByVal idObject As Long, ByVal idChild As Long, ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long
Dim ObA As IAccessible
Dim LRet As Long
Dim V As Variant
Dim s As String, s1 As String, sName As String
On Error Resume Next
Dim pxLeft As Long, pyTop As Long, pcxWidth As Long, pcyHeight As Long
pxLeft = 0
pyTop = 0
pcxWidth = 0
pcyHeight = 0
‘Select Case LEvent
‘Case SYS_FOREGROUND, SYS_ALERT, OB_FOCUS, OB_SELECTION, OB_VALUECHANGE
LRet = AccessibleObjectFromEvent(HWnd, idObject, idChild, ObA, V)
If LRet = 0 Then
With F1
sName = ObA.accName(V)
.Text1(0).Text = sName .Text1(1).Text = ObA.accDescription(V)
s1 = ObA.accValue(V)
.Text1(2).Text = s1
.Text1(3).Text = ObA.accRole(V)
.Text1(4).Text = ObA.accState(V)
RECT = ObA.accLocation(pxleft, pytop, pcxwidth, pcyheight, V)
End With
If (ObA.accState(V) And STATE_UNAVAILABLE) Then
s = » disabled»
End If
If LEvent = OB_VALUECHANGE Then
s = s1 & s
Else
s = sName & s
Источник
Thread: VBA module call in userform to diff sheets error: «expected function or variable»
Thread Tools
Display
VBA module call in userform to diff sheets error: «expected function or variable»
new here and would like to ask if someone could possibly check my code to see where i’m making a mistake.
first, i’ve created a form with two textboxes and two buttons that will go and get two different directories and the associated files. this is done through a call to a function that loads the dir to the textboxes.
then, i am trying to have a button get the two files that are loaded into the textboxes for comparing/diffing by a module.
a button to call a function to navigate dir and get the file loaded into textboxe
up to here, the code is ok. can do better with the code, but here’s where problems occur. i’d like to pass the directories as objects into the module to diff and there’s an error: «expected function or variable»
button that executes module to diff:
i know that i’ve changed myPath1 and myPath2 to Workbooks, where I’ve had them as strings before
So my question is. can someone please assist in seeing where i’m going wrong? i guess i’m not sure why there’s an error at all. much appreiated. and sorry for the verbose post.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
If the error is on «getTheWorkbooksToCompare», then try this small change:
Re: VBA module call in userform to diff sheets error: «expected function or variable»
will have the same issue. do you have any suggestions?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Wouldn’t the fact that these two variables:
are dim’d within the selectFile function cause a problem when using them here:
I might be misunderstanding the flow of the code.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
hi. i’m not sure that it would, but please correct me if i am wrong. because i believe i’m loading the file path into the textbox and then grabbing that file path from the textbox to pass as an object to the function for diffing. i guess i’m getting a little confused since i’ve tried so many ways to pass the object that i’m confusing myself now.
i’ve also tried to change the module call as suggested to
though, i believe i tried this a while ago without success.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Please post one continuous listing of your code. It is hard to discern what your code is from all these fragments.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Re: VBA module call in userform to diff sheets error: «expected function or variable»
DIR returns a string, do not use the SET keyword, that is for objects
depending what you want to do
if you are trying to open the fileNamePath1 then
where wb1 is a workbook or object
but if you are doing this from within Excel, you do not need (in most cases) to create an additional instance of excel, just use the application object
Dim book1 As Workbook
Dim book2 As Workbook
Call getWorkbooksToCompare(book1, book2)
this looks like you are passing empty workbook objects to someother procedure, which i an sure would give an error
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
i’ve taken you suggestions and the code went further into the area that i’v not listed, which was the diff area. i get an error of: «for each object may only iterate over a collection object or an array»
here is the code that i left out to diff files
also. thank you for your assistance
Re: VBA module call in userform to diff sheets error: «expected function or variable»
so i think i fixed some of the above issues with everyone’s help. i now have an error at the above while loop that reads: «object doesn’t support this property or method». the error occurs on the commented while loop and the uncommented version
Re: VBA module call in userform to diff sheets error: «expected function or variable»
myWorksheetCounter is now a numeric value
you can loop through the worksheets in several ways, the two most common would be
you are trying several codings, but mixing which you work with further down
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
i saw the same while i was working through the logic. i think i’m a bit stumped on the language. is there an example that you could please provide?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
i did not test this
Note using usedrange to compare worksheet areas can be unreliable, as it may extend past the rows or columns of values
unless you are sure that the data is always the same rows or columns, even an equal count of cells may not mean that the data area matches, you may need to count either rows or columns are equal as well
depending on the size of the used range, it may be much faster to work with arrays of the data
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
hi. tried the suggestion and received a run time error 438: object doesn’t support this property or method. the starting while loop at
is highlighted. am i missing something here in my types?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
you can not compare anything with NULL
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
thank you. that helped.
so, i’ve made the change and received an error of: run-time error 91 object variable or with block variable not set, where the
also, if you could please shed some light on my data structures here.
Last edited by whatever; Nov 9th, 2014 at 01:11 PM .
Re: VBA module call in userform to diff sheets error: «expected function or variable»
not at all, of course you can assign values to a variable within a loop
definitely the set keyword should not be used as worksheets.count returns an integer, not an object.
the error appears to mean there is no activeworkbook at that time, which is a bit strange
please explain what you want to know
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
in the same thought process as you had mentioned about there is no activeworkbook at that time. this part is confusing me, because there should be an activeworkbook that’s passed.
so i’m thinking i’m doing something incorrectly in passing a reference or value to the workbook object. i’m not very proficient in the semantics of vb and some configurations i would expect to work are not working.
ultimately, i’d like to see a third workbook created with a diff, which is not happening.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
i think i’ve been able to get passed most of the issues that were plaguing me before. the only issue i’m having now, is that i’m not seeing my diff in the new (3rd) workbook. anyone have any ideas why that may not be occurring? much appreciated
Re: VBA module call in userform to diff sheets error: «expected function or variable»
this does not make sense
for cell = 1 to must be another number or a variable or cell containing a number
cell would then always then be a number, not a range object
also it is good practice not to use reserved words (like cell) as names for variables
better to use descriptive names or abbreviations
better in this case to use for each cel in thisrange
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
thanks. that fixed the loop issue.
do you have any ideas on the If statement that you had pointed out earlier? i’ve tried several ways and i’m getting an object required error.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Try changing «cell» to «cel» as per Pete’s suggestion. When you get the error, can you confirm that it’s not «myWorksheetObj2» that is the problem?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
hi. yes, i made the change as he had suggested. here is the new version of code without errors, but no output to the 3rd workbook. hmmm.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Can you zip and attach your workbooks, with the entire current code, if not overly sensitive?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
i’ll remove some things but keep the idea there. is that ok?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Re: VBA module call in userform to diff sheets error: «expected function or variable»
so i can send the information that i’ve made. just not the rest. if that’s ok. how would i go about uploading?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
you have to zip a workbook to attach it (in Advanced mode).
Re: VBA module call in userform to diff sheets error: «expected function or variable»
so after some assistance from vbfbryce. i’m a lot further and just have a small issue of trying to get the proper output.
1) would like to take the iteration that’s already occurring and print out the names of the files and sheets, if there is a difference of a cell between the sheets
2) also, would like to print out the cell that’s from both sheets in column A and another in column B, to display the side by side diff.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
where would you like to print these?
test if this does anything like what you want, make sure to assign rw a starting value before looping, else will cause an error
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Re: VBA module call in userform to diff sheets error: «expected function or variable»
hi. assigning rw a value such as rw = 0?
Re: VBA module call in userform to diff sheets error: «expected function or variable»
There isn’t a «row 0,» so you would want to initialize it to 1, not 0.
Re: VBA module call in userform to diff sheets error: «expected function or variable»
hi everyone. i think i’m a lot closer now. i’m trying to figure out if there’s a way to go from sheet tab 1 to n? i was trying this with a standard for loop:
Re: VBA module call in userform to diff sheets error: «expected function or variable»
Not exactly sure what you mean, but if you’re wanting to do something with the first «x» tabs (worksheets) in a workbook, try something like this:
Re: VBA module call in userform to diff sheets error: «expected function or variable»
is there a way to save the compared worksheets into one workbook? currently, the wbNew.SaveAs creates a workbook for each workbook. i’ve tried placing the wbNew.SaveAs inside the main if statement and at each for loop. so i’m wondering if there’s a better way to
Re: VBA module call in userform to diff sheets error: «expected function or variable»
as you are looping sheets and looping cells within sheets, you would need to open the new workbook before starting to loop anything and make sure not to open any further workbooks within any loop, you do not need to save the new workbook until after the outer loop, but it would not greatly affect any thing if additional saves are performed, make sure not to reset the value of rw within the any loop or it would cause some existing values to be overwritten
add workbook
rw = 8
add sheet headers row 7
loop sheets
loop cells
if cell different, then write details to workbook on row rw, increase rw by 1
next inner loops
you could increase rw by 1 here to leave a line space between worksheets
next outer loop
save and close new workbook
Last edited by westconn1; Nov 12th, 2014 at 03:25 PM .
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Источник
Sub test()
'
' test Macro
'
' Copy total poundage up
ActiveCell.Offset(0, 1).Range("A1").Select
selection.End(xlDown).Select
selection.End(xlDown).Select
selection.Copy
selection.End(xlUp).Select
ActiveCell.Offset(-1, 0).Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
' Extended prices
ActiveCell.Offset(1, 0).Range("A1").Select
selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=RC[-8]*RC[-5]"
' If there is more than one row to summarize, it copies the formula for all the rows
If selection.Offset(1, -1).Range("A1") <> 0 Then
ActiveCell.Select
selection.Copy
ActiveCell.Offset(0, -1).Range("A1").Select
selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Range("A1").Select
Range(selection, selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
End If
' weighted average
ActiveCell.Select
ActiveCell.Offset(-1, 0).Range("A1").Select
selection.End(xlToLeft).Select
ActiveCell.Offset(0, -1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=SUM(R[1]C[7]:R[3]C[7])/RC[1]"
ActiveCell.Select
' pasting values, so can delete cells
selection.Copy
selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Paste
Application.CutCopyMode = False
' selecting the cells to be deleted - this code was what put the program over the edge
ActiveCell.Offset(1, -8).Select
Range(selection, selection.End(xlDown)).Select
Range(selection, selection.End(xlToRight)).Select
Range(selection, selection.End(xlToRight)).Select
Range(selection, selection.End(xlToRight)).Select
End Sub
-
05-21-2014, 12:55 PM
#1
Registered User
Compile Error Expected Function or Variable
Hi,
I’m fairly new to VBA so please bare with me. I’ve basically created this macro which print screens and saves the file into pdf looking up which sheet and range in a tab that i created. I’m however getting this compile error with the «Sub test()» turning yellow:
Any ideas?
Last edited by shiser; 05-22-2014 at 09:19 AM.
-
05-21-2014, 12:56 PM
#2
Forum Contributor
Re: Compile Error Expected Function or Variable
Sheet35 is a variable you did not declare what is in it.
Do you means Sheets(«Sheet35») or Sheets(35)?
-
05-21-2014, 12:59 PM
#3
Re: Compile Error Expected Function or Variable
Used in that fashion, Sheet35 must be the CodeName of a sheet, which is what appears to the left of the sheet name in the Project Explorer window. In a new workbook with two sheets, you would see
Sheet1 (Sheet1)
Sheet2 (Sheet2)Change the name of Sheet1 to Bob, and you’d see
Sheet1 (Bob)
Sheet2 (Sheet2)After doing that, you could refer to the first sheet as either Sheet1, or Worksheets(1), or Worksheets(«Bob»)
Last edited by shg; 05-21-2014 at 01:02 PM.
Entia non sunt multiplicanda sine necessitate
-
05-21-2014, 01:11 PM
#4
Registered User
Re: Compile Error Expected Function or Variable
I’ve called the worksheet «test» and I’m getting the same error. I’ve adjusted it as:
I’ve also tried:
which I believe is the same thing. I still get the same error annoyingly
-
05-21-2014, 01:33 PM
#5
Re: Compile Error Expected Function or Variable
Originally Posted by shiser
I’ve called the worksheet «test» and I’m getting the same error. I’ve adjusted it as:
I’ve also tried:
which I believe is the same thing. I still get the same error annoyingly
The first line should never generate a compile error; it would generate a runtime (subscript) error if there is no worksheet named test in the active workbook.
The second line is missing a closing quote after test.
Last edited by shg; 05-22-2014 at 04:17 PM.
-
05-22-2014, 04:19 AM
#6
Registered User
Re: Compile Error Expected Function or Variable
I’m confused then because I’m getting a compile error.
The second code was written in heist on the forum but I’ve had the correct formula in the macro.
Wouldn’t the worksheet part of the code turn yellow if that was the issue? Just to clarify, the «Sub test()» is getting the error and turning yellow.
-
05-22-2014, 06:50 AM
#7
Registered User
Re: Compile Error Expected Function or Variable
I think I know what the problem is! Its this code:
Basically, what I want it to do is look up the sheet dependent on what I have in my tab.:
and the lookup cell contains for example:
Which is located in cell C4. With my Macro stating i = 4 and sTab location being (i, 3), it should be picking up the correct cell I think.
-
05-22-2014, 07:10 AM
#8
Re: Compile Error Expected Function or Variable
Remember what the dormouse said
Feed your head
-
05-22-2014, 08:00 AM
#9
Registered User
Re: Compile Error Expected Function or Variable
«subscript out of range»
So close to figuring this out!
-
05-22-2014, 08:14 AM
#10
Re: Compile Error Expected Function or Variable
That means sTab does not contain the tab name of one of your worksheets.
-
05-22-2014, 09:18 AM
#11
Registered User
Re: Compile Error Expected Function or Variable
Originally Posted by romperstomper
This worked. I mistakenly had quotations in this line. Thanks!
-
#1
I’m receiving the following error message in one of my modules/procedures “Compile error — Expected variable or procedure, not module.»
Here’s the background and code:
The module CheckForNulls checks for null values in form fields. The code is in a module because it should be available to all forms “on the fly”. The module is called by Private Sub cmdSend_Click() event, where it says
Cancel = CheckForNulls(me.form).
Due to the error message, I tried changing this to the following, but still get the error
Dim X As Boolean
X = CheckForNulls(Me.Form)
Back on the form, if CheckForNulls = False (no incomplete records were found), then some other routines take place.
PHP:
Public Function CheckForNulls(frm as form) as boolean
Dim ctl As Control
Dim intMsgResponse As Integer
' Loop through all the controls on the form
For Each ctl In frm.Controls
' Check the tag property
If ctl.Tag = "RequiredField" Then
' Check this control has a value
If ctl = "" Or IsNull(ctl) Then
' No Value - Cancel the update event
CheckForNulls = True
'Exit loop when an incomplete required field is found
Exit For
End If
End If
Next
' Check to see if a required field was blank and inform the user
If CheckForNulls = True Then
MsgBox "Please fill in all required fields."
End If
End Function
Could someone look at this to help pinpoint what is wrong?
Christine
-
#2
1 This should be a sub not a function (it doesnt have the function to return the boolean to your original code, it handles the message and all itself).
2 Your Module has the same name as your function, get a naming convention in place (search the forum if that sounds alien to you)! Rename the module to mdlCheckForNulls
Greetz
-
#3
Complile error — Expected variable or procedure, not module
Thank you for that. Sorry if this is going to be a silly question, but I’m very new to all this.
I’ve changed the name of the module, as you suggested and changed the code to this
Public Sub CheckForNulls(frm As Form)
…..
End Sub
Everything else in the module is the same. It still doesn’t work and I’m sure it’s probably something silly.
I had two options for «calling» the procedure, none of which work:
1. Cancel = mdlCheckForNulls(Me.Form)
2. Dim X As Boolean
X = CheckForNulls(Me.Form)
After checking for nulls and control returns to my form, I want to do some stuff if CheckForNulls = False:
If CheckForNulls = False Then
So, you see I’m still in the dark. Your further assistance will make the end of this work day a success. Hope to hear from you soon!
Christine
-
#4
Still awaiting help — Compile error: Expected variable or procedure, not module
I hate to appear impatient, but could someone respond soonest concerning my problem and last post? I played with the code this weekend, to no avail.
Thanks so much,
Christine
-
#5
I don’t know why namlian said it should be a Sub I don’t know; he must have been having an off day as it perfectly obvious that it is — and should be — a function.
Don’t send Me.Form to the function. Send Me
-
#6
Thank you. I’m still getting the same compile error.
In the form that calls the function, I’ve changed it as I *think* you said to do about changing the line to «send» the function call:
Private Sub cmdSend_Click()
‘ Call the module mdlCheckForNulls to ensure all form fields are complete.
Cancel = mdlCheckForNulls(Me)
In the module (called mdlCheckForNulls), it reads…
Public Function CheckForNulls(frm As Form) As Boolean
Dim ctl As Control
Dim intMsgResponse As Integer
‘ Loop through all the controls on the form
For Each ctl In frm.Controls
…etc.
End Function
-
#7
Can you upload a copy of the relevant components in a database? Change any confidential data to dummy data.
Rich
Guest
-
#8
If Not mdlCheckForNulls(Me) Then
Cancel = True
End If
??????????
-
#9
Thanks so much for looking at this for me!
Cheers,
Christine
-
#10
Oops, the file didn’t attach. Here it is.
BTW, I tried Rich’s suggestion
If Not mdlCheckForNulls(Me) Then
Cancel = True
End If
but still receive the same error.
-
testCARSystem.zip
57.4 KB · Views: 132
-
#11
looks like you have been merging to functions somehow try
Public Function CheckForNulls(frm As Form) As Boolean
Dim ctl As Control
Dim intMsgResponse As Integer
CheckForNulls = False
‘ Loop through all the controls on the form
For Each ctl In frm.Controls
‘ Check the tag property
If ctl.Tag = «RequiredField» Then
‘ Check this control has a value
If ctl = «» Or IsNull(ctl) Then
‘ No Value — Return True
CheckForNulls = True
‘Exit loop when an incomplete required field is found
Exit For
End If
End If
Next
End Function
Peter
-
#12
Wouldn’t it be simpler just to set the fields’ Required property to True at table level?
-
#13
You still had the wron call from the form,
Cancel = mdlCheckForNulls(Me)
should be
Cancel = CheckForNulls(Me)
Also you have not dim’ed the Cancel as a variable so that will thow you an error next!
Peter
Edit — In fact as Cancel is a reserved word it is probably better not to use it anyway!
-
#14
le error — Expected variable or procedure, not module
Ordinarily, yes. However, at the request of users, I’ve had set up the form so that users can create a Corrective Action Request (CAR) and leave it incomplete until a later time when they can come back to edit it. Unfortunately, this will happen quite frequently.
When they press the Send button, this is when the checks need to be made to ensure they haven’t left anything blank.
Christine
-
#15
Expected variable or procedure, not module — SOLVED!
I am so pleased to report that the problem is solved! Many, many thanks to all of you who helped. Peter’s last comment about Cancel et al was the final piece in the puzzle. You guys are the best!
Christine
XOXOX!!
|
|