Compile error expected variable

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() ...

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's user avatar

Josh Crozier

228k54 gold badges386 silver badges301 bronze badges

asked Apr 24, 2014 at 16:41

user3569764's user avatar

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 Rutkowski's user avatar

Artur RutkowskiArtur Rutkowski

4374 gold badges9 silver badges16 bronze badges

It is possible to make your code fail in two different ways:

  1. Place a very large value in D10
  2. 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 Student's user avatar

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's user avatar

Nippey

4,65835 silver badges44 bronze badges

answered Oct 23, 2014 at 11:47

Peter Rush's user avatar

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

cssyphus's user avatar

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
Регистрация: 27.08.2018

#1

27.08.2018 16:50:39

Добрый день, уважаемые форумчане!

Прошу подсказать — написал такой макрос и привязал его к кнопке. При написании с отладкой проблем не было, режим был доступен.
Сейчас при попытке сделать дебаг, возникает Compile Error: Expected Function or Variable — режим не запускается.

Просьба подсказать, в чем косяк.

Код
Sub DataTransfer()
'
' DataTransfer Макрос
'
    
    Dim strFileToOpen
    Dim wrkBook As Workbook
    Dim columnN As Integer, rowN As Integer
    Dim DateType As Variant, CodeType As Variant
    Dim i As Integer, Ind As Integer
    Dim s As String
    Dim lastRow As Integer
    
    'Адреса файлов  -  индекс файла должен четко соответствовать коду БЕ
    Dim Source(1 To 6) As String

        Source(1) = ThisWorkbook.Path & "Д.xlsx"
        Source(2) = ThisWorkbook.Path & "Р.xlsx"
        Source(3) = ThisWorkbook.Path & "Ф.xlsx"
        Source(4) = ThisWorkbook.Path & "Н.xlsx"
        Source(5) = ThisWorkbook.Path & "Ла.xlsx"
        Source(6) = ThisWorkbook.Path & "УК.xlsx"
    
    
    ' Поиск даты из ячейки А1 в строке 9 для копирования данных
    ' ВАЖНО!!! Предполагается, что столбцы в сводном файле и файле БЕ совпадают -
    ' т.е. столбцы с датами соответствуют друг другу
    Set DateType = ThisWorkbook.Worksheets(1).Rows(9). _
                        Find(ThisWorkbook.Worksheets(1).Cells(2, 9).Value, , xlValues, xlWhole)
    If Not DateType Is Nothing Then
        columnN = DateType.Column
    Else
    MsgBox "Дата не найдена"
    End If
    
    'запускаем цикл поэтапной обработки файла
    For Ind = 1 To UBound(Source)
    
    'назначаем файл в работу
    strFile = Source(Ind)
    Set wrkBook = Workbooks.Open(strFile)
    
    'снимаем защиту с листа
    wrkBook.Worksheets(1).Unprotect 
    wrkBook.Worksheets(1).Columns(columnN).Locked = False
    
    'Определяем последний элемент в столбце
    lastRow = ThisWorkbook.Worksheets(1).Cells(Rows.Count, 9).End(xlUp).Row
    
    'копируем данные
    For i = 9 To lastRow
        If Not ThisWorkbook.Worksheets(1).Cells(i, 1).Value = "" Then
            s = ThisWorkbook.Worksheets(1).Cells(i, 9).Value
            If Left(ThisWorkbook.Worksheets(1).Cells(i, 9).Value, 1) = Ind Then
            
            Set CodeType = wrkBook.Worksheets(1).Columns(9). _
                        Find(ThisWorkbook.Worksheets(1).Cells(i, 9).Value, , xlValues, xlWhole)
            If Not CodeType Is Nothing Then
                        rowN = CodeType.Row
            Else
                        MsgBox "Код " & ThisWorkbook.Worksheets(1).Cells(i, 9).Value & " не найден!"
            End If
            Set CodeType = Nothing
            wrkBook.Worksheets(1).Cells(rowN, columnN).Value = _
                             ThisWorkbook.Worksheets(1).Cells(i, columnN).Value
            End If
        End If
    Next i

    'устанавливаем параметр "защищаемая ячейка" для этих ячеек
    wrkBook.Worksheets(1).Columns(columnN).Locked = True
    wrkBook.Worksheets(1).Protect 
    
    wrkBook.Save
    wrkBook.Close
    Set wrkBook = Nothing
    Next Ind
    MsgBox "Готово!"
End Sub



Изменено: bazboy27.08.2018 20:53:39

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13995
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#2

27.08.2018 16:57:14

Вы хоть напишите в какой строке возникает ошибка. И что значит:

Цитата
bazboy написал:
при попытке сделать дебаг

как Вы его пытаетесь сделать?

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

bazboy

Пользователь

Сообщений: 8
Регистрация: 27.08.2018

#3

27.08.2018 17:04:39

Цитата
Дмитрий(The_Prist) Щербаков написал:
как Вы его пытаетесь сделать?

указатель в код и F8

 

Допустим. А ошибка-то в какой строке?

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

bazboy

Пользователь

Сообщений: 8
Регистрация: 27.08.2018

в том-то и дело, что ничего не подсвечивает

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

#6

27.08.2018 17:37:29

Цитата
bazboy написал:
в том-то и дело, что ничего не подсвечивает

Видиш суслика? Нет.
А он есть)))

 

Alemox

Пользователь

Сообщений: 2183
Регистрация: 25.02.2013

#7

27.08.2018 18:50:53

Если у вас в модуле стоит
Option Explicit
то у вас не все переменные описаны, например
strFile
А тут что происходит

Код
If Not DateType Is Nothing Then
        columnN = DateType.Column
    Else
        MsgBox "Дата не найдена"
End If

у вас переменная не найдена, а код дальше продолжает своё действие, и далее упирается опять в ошибку когда выполняет строку

Код
wrkBook.Worksheets(1).Columns(columnN).Locked = False

потому что ColumnN=0
Я думаю, что в Else выше недостаточно просто Msgbox.
Дальше смотреть не стал.

Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
А в том, чтобы писать программы, работающие при любом количестве ошибок.

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 13995
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#8

27.08.2018 20:40:05

Цитата
bazboy написал:
При написании с отладкой проблем не было

если почитать, то раньше как-то иначе отладку проводили, не по F8? В какой момент перестало работать?
Проверьте, что открываемые файлы открываются НЕ в режиме защищенного просмотра. Иначе сразу после этой строки:

Код
Set wrkBook = Workbooks.Open(strFile)

переменная wrkBook будет Nothing и далее посыпят ошибки.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

bazboy

Пользователь

Сообщений: 8
Регистрация: 27.08.2018

#9

28.08.2018 16:05:40

Добрый день!

Цитата
ivanok_v2 написал:
Видиш суслика? Нет.А он есть)))

Именно))

Цитата
Alemox написал:
Если у вас в модуле стоитOption Explicitто у вас не все переменные описаны, напримерstrFile

Нет Option Explicit не стоял, спасибо — установил Require Variable Declaration в настройках.
strFile удалил, теперь сразу

Код
Set wrkBook = Workbooks.Open(Source(Ind))
Цитата
Alemox написал:
Я думаю, что в Else выше недостаточно просто Msgbox.

Спасибо, поправил — теперь в случае невыполнения условия сразу к закрытию после сообщения.

Цитата
Дмитрий(The_Prist) Щербаков написал:
если почитать, то раньше как-то иначе отладку проводили, не по F8? В какой момент перестало работать?

так и проводил, после выходных перестало  :D
Поскольку в целом весь макрос отладил и с моими файлами все работало, повесил его на кнопку — думаю что, где-то в этот момент все и произошло.
Причем, получилось не с первого раза — первый раз вешал Лист1.DataTransfer — что-то не пошло.
Второй раз переназначал на кнопку — уже назывался DataTransfer. При этом возможно что-то предложило сделать, но сейчас не могу вспомнить.
Сразу подозрений не возникло — все отрабатывало.

Дмитрий, понимаю, что с этого походу надо было начинать, но только сегодня осознал  :oops:

Изменено: bazboy28.08.2018 16:06:01

 

bazboy

Пользователь

Сообщений: 8
Регистрация: 27.08.2018

#10

28.08.2018 16:08:00

Цитата
Дмитрий(The_Prist) Щербаков написал:
Проверьте, что открываемые файлы открываются НЕ в режиме защищенного просмотра.

Проверил, нормально открываются — думаю, изначально были бы проблемы. Через кнопку макрос отрабатывает.

 

Поместите код макроса из модуля листа в стандартный модуль. Тогда F8 будет работать.
Скорее всего у Вас кнопка сделана на основе ActiveX — лучше по возможности избегать этого и сделать кнопку из обычной автофигуры. Это надежнее.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

bazboy

Пользователь

Сообщений: 8
Регистрация: 27.08.2018

#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 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

              End 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.

Содержание

  1. Compile error expected function or variable
  2. Answered by:
  3. Question
  4. Compile error expected function or variable
  5. Answered by:
  6. Question
  7. Compile Error:- expected function or variable problem
  8. Compile Error:- expected function or variable problem
  9. Re: Why is this Macro not working?
  10. Re: Why is this Macro not working?
  11. Re: Macro — Code Problem?
  12. Re: Macro — Code Problem?
  13. Re: Macro — Code Problem?
  14. Re: Compile Error:- expected function or variable problem
  15. Re: Compile Error:- expected function or variable problem
  16. Re: Compile Error:- expected function or variable problem
  17. Re: Compile Error:- expected function or variable problem
  18. Re: Compile Error:- expected function or variable problem
  19. Re: Compile Error:- expected function or variable problem
  20. Re: Compile Error:- expected function or variable problem
  21. Re: Compile Error:- expected function or variable problem
  22. Compile error expected function or variable
  23. Лучший отвечающий
  24. Вопрос
  25. Thread: VBA module call in userform to diff sheets error: «expected function or variable»
  26. VBA module call in userform to diff sheets error: «expected function or variable»
  27. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  28. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  29. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  30. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  31. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  32. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  33. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  34. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  35. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  36. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  37. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  38. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  39. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  40. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  41. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  42. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  43. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  44. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  45. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  46. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  47. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  48. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  49. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  50. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  51. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  52. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  53. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  54. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  55. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  56. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  57. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  58. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  59. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  60. Re: VBA module call in userform to diff sheets error: «expected function or variable»
  61. 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

  1. 05-21-2014, 12:55 PM


    #1

    shiser is offline


    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.


  2. 05-21-2014, 12:56 PM


    #2

    slx is offline


    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)?


  3. 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


  4. 05-21-2014, 01:11 PM


    #4

    shiser is offline


    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


  5. 05-21-2014, 01:33 PM


    #5

    Re: Compile Error Expected Function or Variable

    Quote Originally Posted by shiser
    View Post

    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.


  6. 05-22-2014, 04:19 AM


    #6

    shiser is offline


    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.


  7. 05-22-2014, 06:50 AM


    #7

    shiser is offline


    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.


  8. 05-22-2014, 07:10 AM


    #8

    Re: Compile Error Expected Function or Variable

    Remember what the dormouse said
    Feed your head


  9. 05-22-2014, 08:00 AM


    #9

    shiser is offline


    Registered User


    Re: Compile Error Expected Function or Variable

    «subscript out of range»

    So close to figuring this out!


  10. 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.


  11. 05-22-2014, 09:18 AM


    #11

    shiser is offline


    Registered User


    Re: Compile Error Expected Function or Variable

    Quote Originally Posted by romperstomper
    View Post

    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. :confused:

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!!

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • [RESOLVED] Compile Error: Expected Function or Variable

  1. Apr 18th, 2010, 01:07 AM


    #1

    johnsonlim026 is offline

    Thread Starter


    New Member


    Resolved [RESOLVED] Compile Error: Expected Function or Variable

    Hi, i am new to vb6 and this is my first time deal with vb6
    I have created from A and form B. In form A i call function X in form B.
    And it is workable.

    However, this is i have a project that is written by other programmer , i face this error: Compile Error: Expected Function or Variable . when a function call a public function in other form.
    I not yet even step into the coding and this error has appear.

    Here is the coding in the calling form

    Code:

    Dim lofrmImport As New frmImport
    If lofrmImport.cmdAddWEB(vbTab) Then
                            
    End If

    Here is the coding for the function to be called.

    Code:

    Public Sub cmdAddWEB(Optional psDelimiter As String = vbTab)
    
    Dim lbLoaded As Boolean
    Dim lbVerify As Boolean ' Verify status
    Dim llCurrent As Long   ' Pointer to file position
    Dim lnCount As Integer
    Dim loListImport As MSComctlLib.ListItem
    Dim loListStatus As MSComctlLib.ListItem
    Dim llFNum As Long
    Dim lnTag As Integer    ' Tag pointer
    Dim llLine As Long          ' Line number
    Dim lsLine As String * MAX_LINE_LENGTH
    Dim lsFileArray() As String
    Dim lsFileName As String
    Dim nFiles As Integer
    Dim lsFields() As String
        
        'terri If automateOn Then
        If gbAutomateOn Then
            lbLoaded = False
            On Error GoTo 0
            'goSlrError.Trace "AddLog recorded for " & gsFileName
            WriteLog 1, "AddLog recorded for " & gsFileName   'Open Logfile, for cmdAdd recording
            GoTo Automate
        End If
    
        dlgCommon.CancelError = True
        dlgCommon.DialogTitle = "Select import file"
        dlgCommon.Filter = "All Files (*.*)|*.*|Text Files (*.txt)|*.txt"
        dlgCommon.Flags = cdlOFNExplorer + cdlOFNFileMustExist + cdlOFNReadOnly + cdlOFNAllowMultiselect
        dlgCommon.FilterIndex = 2
        dlgCommon.CancelError = False
        dlgCommon.ShowOpen
    
        On Error GoTo ErrorHandler
    
    Automate:
        'terri If automateOn Then
        If gbAutomateOn Then
            ReDim lsFileArray(1)
            lsFileArray(1) = gsFileName     'Assign commandline arguement
        Else
            lsFileArray = GetAllFileNames(dlgCommon.FileName)
        End If
    
        On Error GoTo 0
        For nFiles = 1 To UBound(lsFileArray)
            If UBound(lsFileArray) = 1 Then
                lsFileName = lsFileArray(nFiles)
            Else
                ' Array 1 contains the directory of the files.
                If nFiles > 1 Then
                    lsFileName = lsFileArray(1) & "" & lsFileArray(nFiles)
                Else
                    lsFileName = ""
                End If
            End If
            ' Check whether entry is already in
            lbLoaded = False
            For lnCount = 1 To lvwImport.ListItems.count
                If lvwImport.ListItems(lnCount).Text = lsFileName Then
                    lbLoaded = True
                End If
            Next
    
            ' Display each file in List View
            If Not lbLoaded Then
                ' Process each file, verify for correctness
                lbVerify = True
                If Trim$(lsFileName) <> "" Then
                    Set loListImport = lvwImport.ListItems.Add(, , lsFileName)
                    StatusBar "Verifying file " & lsFileName
                    llFNum = FreeFile
                    llLine = 0
                    Open lsFileName For Binary Access Read Shared As #llFNum
                    barProgress.Max = LOF(llFNum)
                    barProgress.Value = 0
                    Do While Not EOF(llFNum)
                        barProgress.Value = IIf(Loc(llFNum) >= LOF(llFNum), LOF(llFNum), Loc(llFNum))
                        DoEvents
                        ' Increment line number
                        llLine = llLine + 1
    
                        ' Read the PO Input File line by line, including CR & LF
                        Line Input #llFNum, lsLine
                        'Trim out vbTab at the end of the line
                        If Right$(Trim$(lsLine), 1) = psDelimiter Then
                            lsLine = Left$(Trim$(lsLine), Len(Trim$(lsLine)) - 1)
                        End If
                        lsFields() = Split(Trim$(lsLine), psDelimiter)   'Field delimiter is Tab
    
                        ' Hardcode tag to MSGLEVEL2
                        lnTag = 1
    
                        ' Check for valid line, ie. total fields is 54 for PO Input File
                        If UBound(lsFields) + 1 <> mnSize(lnTag) And Trim$(lsLine) <> "" Then
                            lbVerify = False
                            Set loListStatus = lvwStatus.ListItems.Add(, , lsFileName)
                            'Flag error
                            loListStatus.SubItems(1) = CStr(llLine)     ' Line No.
                            loListStatus.SubItems(2) = IIf(UBound(lsFields) > 0, Trim$(lsFields(0)), " ")
                            loListStatus.SubItems(3) = "Invalid line"   ' Status
                            ' Do not proceed further
                            Exit Do
                        End If
                        'terri If automateOn Then
                        If gbAutomateOn Then
                           ' goSlrError.Trace "Line : " & CStr(llLine) & " - " & Trim$(lsFields(0))
                           WriteLog 2, "Line : " & CStr(llLine) & " - " & Trim$(lsFields(0))
                        End If
                        
                        If Loc(llFNum) >= LOF(llFNum) Then
                            ' Exit if read past file size
                            Exit Do
                        End If
                    Loop
                    barProgress.Value = barProgress.Max
                    Close #llFNum
                    
                    If lbVerify Then
                        loListImport.SubItems(1) = "Passed"
                        'terri If automateOn Then
                        If gbAutomateOn Then
                            'goSlrError.Trace "Passed: File process completed. "
                            'goSlrError.Trace "-------------- End of Add Report -------------"
                            WriteLog 2, "Passed: File process completed. "
                            WriteLog 0, "-------------- End of Add Report -------------"
                        End If
                    Else
                        loListImport.SubItems(1) = "Failed"
                        'terri If automateOn Then
                        If gbAutomateOn Then
                            'goSlrError.ErrorTrap "frmImport.cmdAddWEB", "Failed: SlrEdi Import cmdAdd Failed!!"
                            'goSlrError.Trace "------------ End of Add Report ------------"
                            WriteLog 2, "Failed: SlrEdi Import cmdAdd Failed!!"
                            WriteLog 0, "------------ End of Add Report ------------"
                        End If
                        AutoProcessFail "IMPORT FAIL: SlrEdi Import cmdAdd Failed."
                    End If
                    StatusBar ""
                End If
            End If
        Next
        On Error GoTo 0
        Exit Sub
    
    ErrorHandler:
        'terri If automateOn Then
        If gbAutomateOn Then
            AutoProcessFail "IMPORT FAIL: SlrEdi Import cmdImport Failed."
            'goSlrError.ErrorTrap "frmImport.cmdAddWEB", "IMPORT FAIL - SlrEdi Import cmdAdd Failed!!"
            'goSlrError.Trace "------------ End of Add Report ------------"
            WriteLog 2, "Error: IMPORT FAIL - SlrEdi Import cmdAdd Failed!!"
            WriteLog 0, "------------ End of Add Report ------------"
        End If
        
        Dim MyError As Error
        For Each MyError In DBEngine.Errors
        With MyError
            If gbAutomateOn Then
                WriteLog 2, "Error: frmImport.cmdAddWEB - Error Number: " & .Number & ", Description : " & .Description
                'goSlrError.ErrorTrap "frmImport.cmdAddWEB", "Error Number: " & .Number & ", Description : " & .Description
            Else
                MsgBox .Number & " " & .Description
            End If
        End With
        Next MyError
        Screen.MousePointer = vbDefault
        On Error GoTo 0
        Exit Sub
     
    End Sub

    Does anyone has idea on this? Help pls!!


  2. Apr 18th, 2010, 01:59 AM


    #2

    Re: Compile Error: Expected Function or Variable

    Welcome to the forums…

    The second code that you have provided is not a function. It’s a subprocedure. It will not return anything.
    But using this code:

    Code:

    Dim lofrmImport As New frmImport
    If lofrmImport.cmdAddWEB(vbTab) Then
                            
    End If

    VB is expecting for a return value. But since it’s a sub, it won’t return a value.
    So, if you want to simply invoke the sub, you could use this line instead:

    Code:

    Dim lofrmImport As New frmImport
    lofrmImport.cmdAddWEB vbTab
                            
    End If

    Good luck…


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action — video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5″ TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums — Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,…


  3. Apr 18th, 2010, 09:07 PM


    #3

    johnsonlim026 is offline

    Thread Starter


    New Member


    Re: Compile Error: Expected Function or Variable

    Yo, got it !! Thaks akhileshbc !!


  4. Apr 19th, 2010, 12:03 AM


    #4

    Re: [RESOLVED] Compile Error: Expected Function or Variable

    You’re welcome…


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action — video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5″ TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums — Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,…


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • [RESOLVED] Compile Error: Expected Function or Variable


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Compile error expected array vba
  • Compile error else without if vba
  • Compile error duplicate declaration in current scope
  • Compile error dayz что делать
  • Compile error dayz как исправить