Expected function or variable vba ошибка

Добрый день, уважаемые форумчане!Прошу подсказать - написал такой макрос и привязал его к кнопке. При написании с отладкой проблем не было, режим был доступен.Сейчас при попытке сделать дебаг, возникает Compile Error: Expected Function or Variable - режим не запускается.Просьба подсказать, в чем косяк.Код Sub DataTransfer() ' ' DataTransfer Макрос '          Dim strFileToOpen     Dim wrkBook As Workbook     Dim columnN As...
 

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) Щербаков

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

Сообщений: 13997
Регистрация: 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) Щербаков

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

Сообщений: 13997
Регистрация: 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

Источник

  • 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

Понравилась статья? Поделить с друзьями:
  • Expected an indented block python ошибка что значит
  • Exp 00006 internal inconsistency error
  • Exiting pxe rom на ноутбуке lenovo как исправить windows 10
  • Exiting pxe rom на ноутбуке acer как исправить
  • Exiting intel pxe rom как исправить