Compile error expected array vba

Can anyone help me? I have been getting a compile error (...: "Expected Array") when dealing with arrays in my Excel workbook. Basically, I have one 'mother' array (2D, Variant type) and four 'b...

Can anyone help me?

I have been getting a compile error (…: «Expected Array») when dealing with arrays in my Excel workbook.

Basically, I have one ‘mother’ array (2D, Variant type) and four ‘baby’ arrays (1D, Double type). The called subroutine creates the publicly declared arrays which my main macro ends up using for display purposes. Unfortunately, the final of the baby arrays craps out (giving the «Compile Error: Expected Array»). Strangely, if I remove this final baby array (‘final’ — as in the order of declaration/definition) the 2nd to last baby array starts crapping out.

Here is my code:

 Public Mother_Array() as Variant, BabyOne_Array(), BabyTwo_Array(), BabyThree_Array(), BabyFour_Array() as Double 'declare may other variables and arrays, too

Sub MainMacro()
    'do stuff

   Call SunRaySubRoutine(x, y)

    'do stuff

    Range("blah") = BabyOne_Array: Range("blahblah") = BabyTwo_Array
    Range("blahbloh" = BabyThree_Array: Range("blahblue") = BabyFour_Array

End Sub

Sub SunRaySubRoutine(x,y)
    n = x * Sheets("ABC").Range("A1").Value + 1

    ReDim Mother_Array(18, n) as Variant, BabyOne_Array(n), BabyTwo_Array(n) as Double
    ReDim BabyThree_Array(n), BabyFour_Array(n) as Double

    'do stuff

    For i = 0 to n

        BabyOne_Array(i) = Mother_Array(0,i)
        BabyTwo_Array(i) = Mother_Array(2,i)
        BabyThree_Array(i) = Mother_Array(4,i)
        BabyFour_Array(i) = Mother_Array(6,i)
    Next        

End Sub

I have tried to declare all arrays as the Variant type, but to no avail. I have tried to give BabyFour_Array() a different name, but to no avail.

What’s really strange is that even if I comment out the part which makes the BabyFour_Array(), the array still has zero values for each element.

What’s also a bit strange is that the first baby array never craps out (although, the 2nd one crapped out once (one time out of maybe 30).

BANDAID: As a temporary fix, I just publicly declared a fifth dummy array (which doesn’t get filled or Re-Dimensioned). This fifth array has no actual use besides tricking the system out of having the «Compile Error: Expected Array».

Does anyone know what’s causing this «Compile Error: Expected Array» problem with Excel VBA?

Thanks,

Elias

 

Niarah

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

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

#1

01.08.2013 12:04:24

Добрый день коллеги!
Ситуация делаю UserForm где есть выпадающий список с названиями
использую combobox
в него мне нужно добавить список из листа

Написал вот такой код…..
Выдает ошибку Compile error: Expected array
и выделяет Redim preserve rngY(1
если rngY меняю на Вариант
то выделяет ее же и пишет Type mismatch
В общем не могу понять что не так делаю

Код
Private Sub DolgnosList_DropButtonClick()
Dim colDolgnost As New Collection
Dim i%, k%
Dim rngY As String
Dim intROW As Integer

intROW = Worksheets("Должность".Cells(Rows.Count, 1).End(xlUp).Row
Do
i = i + 1
ReDim Preserve rngY(1 To intROW - 1)
rngY(i) = Worksheets("Должность".Cells(i + 1, 1)
Loop Until rngY(i) = intROW - 1

For k = 1 To i - 1
DolgnosList.AddItem rngY(k)
Next k
End Sub
 

Юрий М

Модератор

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

Контакты см. в профиле

А зачем вообще ReDim Preserve? Забирайте в массив и сразу этот массив в ComboBox. Ну или циклом AddItem.

 

KuklP

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

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

E-mail и реквизиты в профиле.

#3

01.08.2013 12:33:20

Цитата
Niarah пишет: что не так делаю

Многое!  :)

Цитата
Юрий М пишет: А зачем вообще ReDim Preserve?

Да еще в цикле. Размерность же не меняется.
Вместо всего того великолепия, одна строчка кода:

Код
Private Sub DolgnosList_DropButtonClick()
    DolgnosList.List = Range("a1:a" & Cells(Rows.Count, 1).End(xlUp).Row).Value
End Sub

И используйте теги для оформления кода.

Изменено: KuklP19.10.2015 16:13:26

Я сам — дурнее всякого примера! …

 

Niarah

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

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

#4

01.08.2013 12:37:47

Цитата
Юрий М пишет:
А зачем вообще ReDim Preserve? Забирайте в массив и сразу этот массив в ComboBox. Ну или циклом AddItem.

М-м-м в первом варианте я задаю rngY как массив ? array ? или new collection
я еще слаб в массивах )

а циклом вот так ?

Код
for i = 1 to introw ' introw = число строк в списке
   dolgnosList.additem worksheets("Должность".cells(i,1)
next i

А потом то что они выберут мне нужно внести в лист
.cells(1,1)=dolgnosList.selected
вот так ?

 

Юрий М

Модератор

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

Контакты см. в профиле

 

Niarah

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

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

 

Sanya_Bars

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

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

Спасибо мало…..
Человек вопрос задал а вы ему так и не ответили а предложили свое решение
Ваш форум читает не только создатель темы но еще многие пользователи интернета по запросу в поисковике
а данное решение мне вот например не подходит
Мне нужно знать где я ошибся чтоб больше не повторять эти ошибки
Так что буду искать дальше в чем я ошибся

 

Юрий М

Модератор

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

Контакты см. в профиле

Почему предложенное решение не подходит? И какая проблема у Вас — как проявляется ошибка?

 

Sanya_Bars

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

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

1.Я свою проблему решил
при создании массива ReDim newarr(…бла бла бла) VBA ругался  .Compile error: Expected array
я ошибочно присвоил переменную as Range для массива newarr
замена переменнной на variant помогла… ну либо просто без объявления
2. мне в коде не нужен UserForm и выпадающий список, а нужен был именно массив для работы с данными, я просто скопировал его
из своего другого кода но там он работал а в новом нет. долго ломал голову. в старом коде Dim далеко в верху

я сам не программист и VBA недели 2 изучаю, так что много детских ошибок ни одного действия без интернета не получилось бы
щас появилось время и я пытаюсь облегчить себе жизнь при помощи VBA
очень часто ошибаюсь с синтаксисом

По поводу темы форума, меняем на variant  массив и дальше начинает ругаться VBA «…пишет Type mismatch…»
дальше надо смотреть где собака порылась [IMG]
……посмотрел….поправте если я не прав чтоб применить ReDim Preserve rngY() нужно сначала создать ReDim rngY()

Niarah

у Вас что-то в цикле напутано, у Вас условие выхода из цикла сравнение значения массива и номера предпоследней строки
такое совпадение редко может у Вас в ячейках буквы вообще
может rngY(i) = intROW — 1 заменить на  i = intROW — 1 или rngY(i) = rngY(intROW — 1)
мне не понятна задача что вы хотите сделать с данными
может нужно просто попробовать другой ЦИКЛ

 

Софья Золкина

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

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

#10

19.10.2015 16:06:26

Sanya_Bars, Спасибо тебе добрый человек. Я долго мучилась с этим «Type mismatch…».
мой исходник выглядел так:

Скрытый текст

После я решила применить ваше указание по поводу «сначала создать ReDim «, но подумав, получается без Preserve мой массив не сохраняет предыдущие вычисления с снова переопределяет массив. Немного подумав я решила обмануть программу и написала так. и все заработало:

Скрытый текст

Удачи всем. Возможно мой опыт тоже кому-то поможет, как мне помог опыт Sanya_Bars.

Изменено: Софья Золкина19.10.2015 16:13:02

Содержание

  1. VBA: Expected Array Error despite No Arrays
  2. 2 Answers 2
  3. Compile error expected array vba
  4. Thread: [RESOLVED] Expected Array.
  5. [RESOLVED] Expected Array.
  6. Re: Expected Array.
  7. Re: Expected Array.
  8. Re: Expected Array.
  9. Re: Expected Array.
  10. Re: Expected Array.
  11. Re: Expected Array.
  12. Re: Expected Array.
  13. Ошибка EXCEL VBA: «Ошибка компиляции: ожидаемый массив»
  14. VBA «Type mismatch: array or user-defined type expected” on String Arrays
  15. 4 Answers 4

VBA: Expected Array Error despite No Arrays

In a sub I’ve made in VBA, which is executed everytime the worksheet changes, the sub calls a function to determine if the user has deleted or changed something they shouldn’t have. The function returns a boolean value to tell the sub if such a critical value has been deleted/edited. This way, the sub knows not to continue executing code.

However, whenever the code executes, VBA returns a Compile Error: Expected array error for the calling of the criticalDataIntact() function, despite there being no arrays used.

Here’s my relevant code,

The cell function outputs an error message via MsgBox and returns Null if it couldn’t find a cell with a specific value in it within a specific worksheet.

2 Answers 2

  • Consider renaming your CriticalDataIntact function to IsCriticalDataIntact .
  • If your Worksheets(CONFIG) worksheet is the same worksheet containing the Worksheet_Change code, consider replacing Worksheets(CONFIG) with Me .
  • If you don’t refer to your criticalDataIntact variable anywhere else in your Worksheet_Change subroutine (i.e. anywhere in the «irrelevant code»), consider removing the variable and just using the return value directly.

Based on the above, your Worksheet_Change routine might look something like:

Consider Option Explicit at the top of the module. I say this because your CriticalDataIntact function contains seemingly undeclared variables: warnWorkloadCell , dangerWorkloadCell (unless these are non-local variables).

I don’t have access to your custom function cell , but presume it is a member of ThisWorkbook for you. Consider changing the name cell to something more descriptive

  • Regarding cell function’s return type, you’ve said it returns either a Range or Null . That sounds like Variant behaviour (my understanding is only Variants can store Null in VBA). But I think this will lead to invalid syntax at the call site, since you can’t Set a Variant to Null (as far as I know).
  • Sounds like what you want is for the return type to be Range — and if a Range can’t be returned, Nothing will be returned (which you can still test for).
  • Based on the above, a better name for your custom function cell might be GetCellOrNothing .
  • So your function might look something like:

    Источник

    Compile error expected array vba

    Вы типы переменных случайным образом выбирали, что ли?
    t объявлено как число, а пытаетесь использовать как массив.
    при том, что массивы в этой задаче нафиг не нужны.

    кстати — не факт, что Ваш цикл выполнится при x=1 (из-за особенностей работы процессоров с вещественными числами).
    вещественные числа в качестве счетчика в цикле for лучше не использовать
    или делать это правильно.

    Вы типы переменных случайным образом выбирали, что ли?
    t объявлено как число, а пытаетесь использовать как массив.
    при том, что массивы в этой задаче нафиг не нужны.

    кстати — не факт, что Ваш цикл выполнится при x=1 (из-за особенностей работы процессоров с вещественными числами).
    вещественные числа в качестве счетчика в цикле for лучше не использовать
    или делать это правильно. ikki

    помощь по Excel и VBA
    ikki@fxmail.ru, icq 592842413, skype alex.ikki

    Ответить

    Сообщение Вы типы переменных случайным образом выбирали, что ли?
    t объявлено как число, а пытаетесь использовать как массив.
    при том, что массивы в этой задаче нафиг не нужны.

    кстати — не факт, что Ваш цикл выполнится при x=1 (из-за особенностей работы процессоров с вещественными числами).
    вещественные числа в качестве счетчика в цикле for лучше не использовать
    или делать это правильно. Автор — ikki
    Дата добавления — 29.11.2014 в 18:26

    Источник

    Thread: [RESOLVED] Expected Array.

    Thread Tools
    Display

    [RESOLVED] Expected Array.

    I’ve just tried to compile my project and all of a sudden some functions that have been working perfectly are causing a compile error:

    another example is where im using a ‘right’.

    The error I get is Compile Error: Expected Array
    and it highlights ‘left’

    Re: Expected Array.

    Its REALLY weird! VB sometimes does absurd things to me, too.

    Try closing and again opening the project and see if it compiles correctly.

    If not (as expected), can you post the value of StrIn variable when the error raises? (Taking the mouse cursor on it will display the value)

    If your problem is solved, then drag down the Thread Tools and mark your thread as Resolved.

    If I helped you solve your problem, inflate some air into my ego by rating my post and adding a comment too.

    For notorious issues (elaborate yourself) contact me via PM. I don’t answer them in the forums EVER.

    Re: Expected Array.

    Two possibilities:

    1. You have recently added a public array named StrIn .. but unlikely
    2. While you were editing, some other error was thrown, which may have
      «confused» the VB Editor. Simply
      • save your app,
      • exit your app (close out the VB session),
      • then relaunch.
      • It might just «self-heal».

    Spoo

    Re: Expected Array.

    @Lone Rebel: Cannot tell you the value as the error is on compiling, not running.
    @Spoo — no self heal Im afraid.

    I am currently doing a global search for and uses of left, but I am sure that I haven’t declared it for anything else: even if I had, its unlikely that I also declared Right!!

    Hmmm. Ill post back my findings in a minute, but Im doubtful

    Re: Expected Array.

    Don’t run your code with Ctrl+F5 man. Just press the F5 button and force-run it. That way you should be able to run your app unless there are syntax errors in it (which is not the case)

    If your problem is solved, then drag down the Thread Tools and mark your thread as Resolved.

    If I helped you solve your problem, inflate some air into my ego by rating my post and adding a comment too.

    For notorious issues (elaborate yourself) contact me via PM. I don’t answer them in the forums EVER.

    Re: Expected Array.

    I was actually trying to compile to an exe to test on another computer, rather than compile and run.

    Anyway when running, (with JUST F5), I get the same error msg.

    Interestingly, in the VB IDE, typing ‘left’ and also ‘right’ no longer prompts me with the accepted arguments, whereas ‘Mid’ does.

    Re: Expected Array.

    Its one strange thing of VB6 compiler.

    It displays the function quick-help when you type Left( or Right( in a MODULE but doesn’t show this help when in a FORM.

    Plus, can you upload your project for us all to be baffled and confused for a while?

    If your problem is solved, then drag down the Thread Tools and mark your thread as Resolved.

    If I helped you solve your problem, inflate some air into my ego by rating my post and adding a comment too.

    For notorious issues (elaborate yourself) contact me via PM. I don’t answer them in the forums EVER.

    Re: Expected Array.

    Ok — its definately something in my code as a new test project works perfectly.

    @Lone Rebel: I cant really upload the project as it 30+ forms, 5 modules etc.

    What should I be looking for?
    I do have the following code which I found somewhere to alter the combo box height.
    Could the enum be a problem?

    The project has been working for some time with this code included though, and indeed if I comment it out, theres no change.

    Источник

    Ошибка EXCEL VBA: «Ошибка компиляции: ожидаемый массив»

    Может кто-нибудь мне помочь?

    Я получаю сообщение об ошибке компиляции (. «Ожидаемый массив») при работе с массивами в моей книге Excel.

    По сути, у меня есть один «материнский» массив (2D, тип Variant) и четыре «детских» массива (1D, тип Double). Вызванная подпрограмма создает публично объявленные массивы, которые мой основной макрос использует для отображения. К сожалению, последний из детских массивов вылетает (выдает «Ошибка компиляции: ожидаемый массив»). Как ни странно, если я удалю этот последний дочерний массив («окончательный» — как в порядке объявления/определения), второй до последнего дочерний массив начнет вылетать.

    Я пытался объявить все массивы как тип Variant, но безрезультатно. Я пытался дать BabyFour_Array() другое имя, но безрезультатно.

    Что действительно странно, так это то, что даже если я закомментирую часть, создающую BabyFour_Array(), в массиве по-прежнему будут нулевые значения для каждого элемента.

    Что также немного странно, так это то, что первый детский массив никогда не вылетает (хотя второй вылетает один раз (один раз из 2).

    BANDAID: В качестве временного исправления я только что публично объявил пятый фиктивный массив (который не заполняется и не переразмеривается). Этот пятый массив не имеет фактического применения, кроме как обмануть систему из-за наличия «Ошибка компиляции: ожидаемый массив».

    Кто-нибудь знает, что вызывает эту проблему «Ошибка компиляции: ожидаемый массив» с Excel VBA?

    Источник

    VBA «Type mismatch: array or user-defined type expected” on String Arrays

    I have a dynamic array of strings DMAs which I declare globally.

    I ReDim the array and assign values to it in the CreateArrayOf function which is of type String() that returns an array of type String()

    When I attempt to pass the DMAs array to another function OutputAnArray

    I get the «Type mismatch: array or user-defined type expected». Throughout the whole process I only mess with string arrays.

    If I take the content of the OutputAnArray function and put it in the parent function where I’m calling it from, everything’s fine.

    Any help is appreciated.

    4 Answers 4

    I changed all String definitions to Variants

    The culprit was still there, so then after a whole lot of attempts to get this to compile, I removed the () from the arrayToOutput parameter and it started working.

    What is still perplexing is the fact that in the following function definition, the () are needed for arrayFrom .

    I really don’t get it, if anyone has any idea of an explanation, I’d love to hear it.

    From the documentation:

    If follows that the function «CreateArrayOf» does not return an array of strings: it returns a variant containing an array of strings.

    The variant cannot be passed as a parameter to a function expecting an array of strings:

    It can only be passed to a function expecting a variant:

    Conversely, DMA is an array of strings:

    DMA can be passed to a function expecting an array of strings:

    And finally, «Type mismatch: array or user-defined type expected» is a generic type mismatch message. When you pass an array of the wrong type, or a variant array, and get the error «array expected», it’s not particularly helpful.

    Источник

    • #2

    The compile error is because you’ve got:

    Code:

    Dim Look_up_Data As String
    ....
    ReDim Look_up_Data(End_line)

    If you’re going to use ReDim once you know how big to make the array, you should declare the variable as an array initially:

    Code:

    Dim Look_up_Data[B][COLOR=#ff0000]()[/COLOR][/B] As String

    BUT ….

    It looks like there might be other problems with your code …

    This line, for example, looks like it’s meant to assign the values in a 2-D range Look_up_data_range to a VBA array. However, this will only work if Look_up_Data is of type Variant, not String or any other type.

    Code:

    Look_up_Data = Look_up_data_range.Value

    Did your colleague have the code working? Have you perhaps made changes to code that was once working?

    • #3

    Doesn’t work here anymore.
    And the assign it to me (as «Chinese Volunteer»)

    Don’t know if it was working at all

    I’ve changed :

    Dim Look_up_data_range() As Range
    Dim Look_up_Data As Variant

    When I run the code now, I’ve got on following line the error message: Can’t assign to array for this line:

    Set Look_up_data_range = ActiveSheet.UsedRange

    • #4

    This line was OK without the brackets:

    Code:

    Dim Look_up_data_range[COLOR=#ff0000][B]()[/B][/COLOR] As Range

    But before we go on making piecemeal changes ….

    The code you’ve posted doesn’t actually do a lot, and it does it in a roundabout way.

    How much more code is there?

    Perhaps the code never worked in the first place. If so, and if you’re not clear what it’s intended to do, then potentially, it’s going to be difficult to «correct».

    • #5

    As I’ve mentioned, they have assign it to me.
    So I don’t know if it has worked at all.

    Below the complete code of the 5 different userforms.

    Userform1:

    Code:

    Private Sub CmdBtn_Check_Shelf_Life_Click()UserForm1.Hide
    UserForm2.Show
    
    
    End Sub
    
    
    Private Sub CmdBtn_Invoeren_Shelf_Life_900_Click()
    UserForm1.Hide
    UserForm3.Show
    
    
    End Sub
    
    
    Private Sub CmdBtn_Local_Company_Click()
    UserForm1.Hide
    UserForm4.Show
    End Sub
    
    
    Private Sub CmdBtn_IQC_Click()
    UserForm1.Hide
    UserForm4.Show
    End Sub
    
    
    Private Sub CmdBtn_View_Excel_Click()
    
    
    Dim Password As String
    Answer = InputBox("Enter Password")
    Password = "xxyyzz"
    
    
    If Answer = Password Then
    Application.Visible = True
    'Worksheets("Shelf_Life_900").Activate
    UserForm1.Hide
    'CmdBtn_View_Excel.Enabled = True
    Else
    CmdBtn_View_Excel.Enabled = True
    End If
    
    
    End Sub

    Userform2:

    Code:

    Option Explicit
    
    Private Sub UserForm_Initialize()
         UserForm1.BackColor = RGB(153, 204, 153)
    Dim v, e
    
    
    With Sheets("LookUpList").Range("A1:A5")
        v = .Value
    End With
    With CreateObject("scripting.dictionary")
        .comparemode = 1
        For Each e In v
            If Not .exists(e) Then .Add e, Nothing
        Next
        If .Count Then Me.CmbBox_Period.List = Application.Transpose(.keys)
    End With
         
    End Sub
    Private Sub CommandButton2_Click()
    
    
    Worksheets("Shelf_Life_900").Activate
    UserForm2.Hide
        
    End Sub
    
    
    Private Sub CommandButton3_Click()
    
    
    UserForm2.Hide
    UserForm1.Show
    
    
    End Sub
    Private Sub CommandButton1_Click()
    
    
    Const Look_up_sheet = "Shelf_Life_900"
    Const CST_First_Line = 2
    Const CST_Item_Col = 1
    Const CST_Shelf_Life_Col = 2
    Const CST_Number_of_Periods = 3
    Const CST_Technical_Responsible_Col = 4
    Const CST_Date_Col = 5
    Const CST_Remarks_Col = 6
    Dim ctl_Cont As Control
    Dim Row As Long
    Dim ws As Worksheet
    Dim MyString As String
    Dim Item As Variant
    Dim Look_up_data_range As Range
    Dim Look_up_Data() As String
    Dim End_line As Integer
    Dim Item_Name As String
    Dim Item_exist As Boolean
    Dim Index_Cell As Integer
    Dim My_Cell As Variant
    Dim x As Range
    
    
    'Check if TxtBox_Item is not empty
    If TxtBox_Item_Number.Text = "" Then
        MsgBox ("Item is not filled in")
        Exit Sub
    End If
    
    
    'Activate look up worksheet
    Worksheets(Look_up_sheet).Activate
    ActiveSheet.Unprotect
    ActiveSheet.AutoFilterMode = False
    
    
    'Read look data
    Set x = Sheets("Request_for_Shelf_Life").Range("A:A").Find(TxtBox_Item_Number.Text)
        If Not x Is Nothing Then TxtBox_TC.Text = x.Offset(, 2).Value
    'Set Look_up_data_range = ActiveSheet.UsedRange
    'End_line = Look_up_data_range.Rows.Count
    'Set Look_up_data_range = ActiveSheet.Range( _
                ActiveSheet.Cells(CST_First_Line, CST_Item_Col), _
                ActiveSheet.Cells(End_line, CST_Item_Col))
    
    
    'Look_up_Data = Look_up_data_range.Value
    ReDim Look_up_Data(End_line)
    Index_Cell = 0
    For Each My_Cell In Look_up_data_range.Cells
        Look_up_Data(Index_Cell) = My_Cell.Value
        Index_Cell = Index_Cell + 1
    Next My_Cell
                    
    'Check If data already present
    Item_Name = TxtBox_Item_Number.Text
    Item_exist = False
    For Each Item In Look_up_Data
        If Item = Item_Name Then
            Item_exist = True
            Exit For
        End If
    Next Item
           
    'Msg box if item exist
    If Item_exist = True Then
        MsgBox (Item_Name & " " & "already excists")
    Else
        
        'Check if CmbBox_Period is not empty
        If CmbBox_Period.Text = "" Then
            MsgBox ("Shelf Life Period is not filled in")
            Exit Sub
        End If
        
        'Check if TxtBox_Shelf_Life is not empty
        If TxtBox_Shelf_Life.Text = "" Then
            MsgBox ("Number of Periods is not filled in")
            Exit Sub
        End If
        
        'Check if Technical Responsible is not empty
        If TxtBox_TC.Text = "" Then
            MsgBox ("Requester is not filled in")
            Exit Sub
        End If
        
        'Fill in the cells
         Application.ActiveSheet.Cells(End_line + 1, CST_Item_Col).Value = TxtBox_Item_Number.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Shelf_Life_Col).Value = CmbBox_Period.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Number_of_Periods).Value = TxtBox_Shelf_Life.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Technical_Responsible_Col).Value = TxtBox_TC.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Remarks_Col).Value = TxtBox_Remarks.Text
         
         'Clear the text boxes
         TxtBox_Item_Number.Text = ""
         CmbBox_Period.Text = ""
         TxtBox_Shelf_Life.Text = ""
         TxtBox_TC.Text = ""
         TxtBox_Remarks = ""
    End If
    
    
    End Sub

    Userform3:

    Code:

    Private Sub CommandButton2_Click()
    
    UserForm3.Hide
    UserForm1.Show
    
    
    End Sub
    
    
    Private Sub CommandButton1_Click()
    
    
    Const Look_up_sheet = "Request_for_Shelf_Life"
    Const CST_First_Line = 2
    Const CST_Item_Col = 1
    Const CST_Request_Col = 2
    Const CST_Department_Col = 3
    Const CST_Responsible_Col = 4
    Dim ctl_Cont As Control
    Dim Row As Long
    Dim ws As Worksheet
    Dim MyString As String
    Dim Item As Variant
    Dim Look_up_data_range As Range
    Dim Look_up_Data() As String
    Dim End_line As Integer
    Dim Item_Name As String
    Dim Item_exist As Boolean
    Dim Index_Cell As Integer
    
    
    
    
    'Check if TxtBox_Item is not empty
    If TxtBox_Item.Text = "" Then
        MsgBox ("Item is not filled in")
        Exit Sub
    End If
    
    
    'Activate look up worksheet
    Worksheets(Look_up_sheet).Activate
    ActiveSheet.Unprotect
    ActiveSheet.AutoFilterMode = False
    
    
    'Read look data
    Set Look_up_data_range = ActiveSheet.UsedRange
    End_line = Look_up_data_range.Rows.Count
    Set Look_up_data_range = ActiveSheet.Range( _
                ActiveSheet.Cells(CST_First_Line, CST_Item_Col), _
                ActiveSheet.Cells(End_line, CST_Item_Col))
    'Look_up_Data = Look_up_data_range.Value
    ReDim Look_up_Data(End_line)
    Index_Cell = 0
    For Each My_Cell In Look_up_data_range.Cells
        Look_up_Data(Index_Cell) = My_Cell.Value
        Index_Cell = Index_Cell + 1
    Next My_Cell
            
            
            
    'Check If data already present
    Item_Name = TxtBox_Item.Text
    Item_exist = False
    For Each Item In Look_up_Data
        If Item = Item_Name Then
            Item_exist = True
            Exit For
        End If
    Next Item
           
    'Msg box if item exist
    If Item_exist = True Then
        MsgBox (Item_Name & " " & "already exists")
    Else
        
        'Check if TxtBox_Requester is not empty
        If TxtBox_Requester.Text = "" Then
            MsgBox ("Requester is not filled in")
            Exit Sub
        End If
        
        'Check if TxtBox_Requester is not empty
        If TxtBox_Afdeling.Text = "" Then
            MsgBox ("Department is not filled in")
            Exit Sub
        End If
        
        'Check if Responsible is not empty
        If TxtBox_TC.Text = "" Then
            MsgBox ("Technical Responsible is not filled in")
            Exit Sub
        End If
        
        'Fill in the cells
         Application.ActiveSheet.Cells(End_line + 1, CST_Item_Col).Value = TxtBox_Item.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Request_Col).Value = TxtBox_Requester.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Department_Col).Value = TxtBox_Afdeling.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Responsible_Col).Value = TxtBox_TC.Text
         
         'Clear the text boxes
         TxtBox_Item.Text = ""
         TxtBox_Requester.Text = ""
         TxtBox_Afdeling.Text = ""
         TxtBox_TC.Text = ""
    End If
    
    
    End Sub

    Userform4:

    Code:

    Private Sub CmdBtn_Local_Company_Click()
    
    
    Const Look_up_sheet = "Local_Company"
    Const CST_First_Line = 2
    Const CST_Item_Col = 1
    Const CST_Division_Col = 2
    Const CST_Responsible_Col = 3
    Const CST_Company_Col = 4
    Dim ctl_Cont As Control
    Dim Row As Long
    Dim ws As Worksheet
    Dim MyString As String
    Dim Item As Variant
    Dim Look_up_data_range As Range
    Dim Look_up_Data() As String
    Dim End_line As Integer
    Dim Item_Name As String
    Dim Item_exist As Boolean
    Dim Index_Cell As Integer
    Dim My_Cell As Variant
    
    
    
    
    'Check if TxtBox_Item is not empty
    If TxtBox_Item_Number.Text = "" Then
        MsgBox ("Item is not filled in")
        Exit Sub
    End If
    
    
    'Activate look up worksheet
    Worksheets(Look_up_sheet).Activate
    ActiveSheet.Unprotect
    ActiveSheet.AutoFilterMode = False
    
    
    'Read look data
    Set Look_up_data_range = ActiveSheet.UsedRange
    End_line = Look_up_data_range.Rows.Count
    Set Look_up_data_range = ActiveSheet.Range( _
                ActiveSheet.Cells(CST_First_Line, CST_Item_Col), _
                ActiveSheet.Cells(End_line, CST_Item_Col))
    
    
    'Look_up_Data = Look_up_data_range.Value
    ReDim Look_up_Data(End_line)
    Index_Cell = 0
    For Each My_Cell In Look_up_data_range.Cells
        Look_up_Data(Index_Cell) = My_Cell.Value
        Index_Cell = Index_Cell + 1
    Next My_Cell
                    
    'Check If data already present
    Item_Name = TxtBox_Item_Number.Text
    Item_exist = False
    For Each Item In Look_up_Data
        If Item = Item_Name Then
            Item_exist = True
            Exit For
        End If
    Next Item
           
    'Msg box if item exist
    If Item_exist = True Then
        MsgBox (Item_Name & " " & "already exists")
    Else
        
        'Check if TxtBox_Division is not empty
        If TxtBox_Division.Text = "" Then
            MsgBox ("Division is not filled in")
            Exit Sub
        End If
        
        'Check if TxtBox_Responsible is not empty
        If TxtBox_Responsible.Text = "" Then
            MsgBox ("Responsible is not filled in")
            Exit Sub
        End If
        
        'Check if TxtBox_Company is not empty
        If TxtBOx_Company.Text = "" Then
            MsgBox ("Local Company is not filled in")
            Exit Sub
        End If
        
        'Fill in the cells
         Application.ActiveSheet.Cells(End_line + 1, CST_Item_Col).Value = TxtBox_Item_Number.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Division_Col).Value = TxtBox_Division.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Responsible_Col).Value = TxtBox_Responsible.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Company_Col).Value = TxtBOx_Company.Text
         
         'Clear the text boxes
         TxtBox_Item_Number.Text = ""
         TxtBox_Division.Text = ""
         TxtBox_Responsible.Text = ""
         TxtBOx_Company.Text = ""
    
    
    End If
    
    
    End Sub
    
    
    
    
    Private Sub CmdBtn_Menu_Click()
    
    
    UserForm4.Hide
    UserForm1.Show
    
    
    End Sub
    
    
    
    
    Private Sub CmdBtn_View_Excel_Click()
    
    
    Worksheets("Local_Company").Activate
    UserForm4.Hide
    
    
    End Sub

    Userform5:

    Code:

    Private Sub CmdBtn_IQC_Click()
    
    UserForm3.Hide
    UserForm1.Show
    
    
    End Sub
    
    
    Private Sub CmdBtn_IQC_Write_Click()
    
    
    Const Look_up_sheet = "IQC"
    Const CST_First_Line = 2
    Const CST_Item_Col = 1
    Const CST_Responsible_Col = 2
    Const CST_Refrigerator_Col = 3
    Dim ctl_Cont As Control
    Dim Row As Long
    Dim ws As Worksheet
    Dim MyString As String
    Dim Item As Variant
    Dim Look_up_data_range As Range
    Dim Look_up_Data() As String
    Dim End_line As Integer
    Dim Item_Name As String
    Dim Item_exist As Boolean
    Dim Index_Cell As Integer
    
    
    
    
    'Check if TxtBox_Item is not empty
    If TxtBox_Item_Number.Text = "" Then
        MsgBox ("Item is not filled in")
        Exit Sub
    End If
    
    
    'Activate look up worksheet
    Worksheets(Look_up_sheet).Activate
    ActiveSheet.Unprotect
    ActiveSheet.AutoFilterMode = False
    
    
    'Read look data
    Set Look_up_data_range = ActiveSheet.UsedRange
    End_line = Look_up_data_range.Rows.Count
    Set Look_up_data_range = ActiveSheet.Range( _
                ActiveSheet.Cells(CST_First_Line, CST_Item_Col), _
                ActiveSheet.Cells(End_line, CST_Item_Col))
    'Look_up_Data = Look_up_data_range.Value
    ReDim Look_up_Data(End_line)
    Index_Cell = 0
    For Each My_Cell In Look_up_data_range.Cells
        Look_up_Data(Index_Cell) = My_Cell.Value
        Index_Cell = Index_Cell + 1
    Next My_Cell
            
            
            
    'Check If data already present
    Item_Name = TxtBox_Item_Number.Text
    Item_exist = False
    For Each Item In Look_up_Data
        If Item = Item_Name Then
            Item_exist = True
            Exit For
        End If
    Next Item
           
    'Msg box if item exist
    If Item_exist = True Then
        MsgBox (Item_Name & " " & "already exists")
    Else
        
        'Check if TxtBox_Responsible is not empty
        If TxtBox_Responsible.Text = "" Then
            MsgBox ("Reponsible is not filled in")
            Exit Sub
        End If
        
        'Check if TxtBox_Refrigerator is not empty
        If TxtBox_Refrigerator.Text = "" Then
            MsgBox ("Refrigerator is not filled in")
            Exit Sub
        End If
        
        
        'Fill in the cells
         Application.ActiveSheet.Cells(End_line + 1, CST_Item_Col).Value = TxtBox_Item_Number.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Responsible_Col).Value = TxtBox_Responsible.Text
         Application.ActiveSheet.Cells(End_line + 1, CST_Refrigerator_Col).Value = TxtBox_Refrigerator.Text
         
         'Clear the text boxes
         TxtBox_Item_Number.Text = ""
         TxtBox_Responsible.Text = ""
         TxtBox_Refrigerator.Text = ""
         
    End If
    
    
    End Sub
    
    
    Private Sub CmdBtn_Menu_Click()
    UserForm5.Hide
    UserForm1.Show
    End Sub
    
    
    Private Sub CmdBtn_View_Excel_Click()
    Worksheets("IQC").Activate
    UserForm5.Hide
    End Sub

    • #6

    As a first step, try replacing all this code (from Sub CommandButton1_Click in UserForm2):

    Code:

    Look_up_Data = Look_up_data_range.Value
    ReDim Look_up_Data(End_line)
    Index_Cell = 0
    For Each My_Cell In Look_up_data_range.Cells
       Look_up_Data(Index_Cell) = My_Cell.Value
       Index_Cell = Index_Cell + 1
    Next My_Cell
                    
    'Check If data already present
    Item_Name = TxtBox_Item_Number.Text
    Item_exist = False
    For Each Item In Look_up_Data
        If Item = Item_Name Then
            Item_exist = True
            Exit For
        End If
    Next Item

    With:

    Code:

    Item_exist = Not IsError(Application.Match(TxtBox_Item_Number.Text, Look_up_data_range, 0))

    I have a block of code as follows:

    Private Sub Find_Latest_Build(strNetInstPath As String, strLocInstPath As String, Src_Folder As String, strZipFl As String, ShellStr As String)
        Dim NewVerNo(3) As Integer, CurrVerNo(3) As Integer, ChkNo As Integer
        Dim StartPos As Integer, i As Integer, j As Integer
        Dim NewVerStr As String, CurrVerStr As String

        For i = 0 To 3
            CurrVerNo(i) = 0
        Next
        CurrVerStr = «»
        Call ParseBldNo(CurrVerStr, CurrVerNo(3))
    End Sub

    Now, I’m trying to pass an integer array (e.g., «CurrVerNo(3)»), but I’m not sure how to do it correctly.  I tried different versions of the ParseBldNo subroutine.  Example 1:

    Private Sub ParseBldNo(VerStr As String, VerNo As Integer)

        Dim StartPos As Integer, i As Integer
        Dim ChkChar As String, ChkMrk As Long

       
        StartPos = 1
        i = 0
        Do While (i <= 3)
            ChkMrk = InStr(1, VerStr, «.»)
            If ChkMrk = 0 Then
                ChkChar = VerStr
            Else
                ChkChar = Left(VerStr, ChkMrk — 1)
            End If
            VerNo(i) = CInt(ChkChar)
            StartPos = ChkMrk + 1
            VerStr = Mid(VerStr, StartPos)
            i = i + 1
        Loop
    End Sub

    The result is a compile error (Expected Array).

    Example #2:  Changed the subroutine header to read:

    Private Sub ParseBldNo(VerStr As String, VerNo(3) As Integer)

    This instantly resulted in a compile error (syntax—Expected ‘)’ )

    Example  #3:  Changed the subroutine header again to read:

    Private Sub ParseBldNo(VerStr As String, ParamArray VerNo() As Variant)

    Running the script this way generates a run-time error 9 message (subscript out of range) at the statement:

    VerNo(i) = CInt(ChkChar)—debugging showed it passed once, but not a second time.

    Example #4:  Revised the first few lines of the subroutine to read:

    Private Sub ParseBldNo(VerStr As String, ParamArray VerNo() As Variant)

        Dim StartPos As Integer, i As Integer
        Dim ChkChar As String, ChkMrk As Long
        ReDim VerNo(3) As Integer

    This generated another compile error (UGH!)—Can’t change data types of array elements

    Since I’ve tried and failed several times, could someone please advise as to the proper approach to passing integer arrays as parameters to subroutines?  I greatly appreciate it as I am somewhat of a «non-expert» to VBA scripting (based on a slew of
    questions posted on this forum).  Thank you very much.


    John J. Bottiger (QA Engineer, Gladiator Innovations LLC)

    1. 05-27-2016, 02:34 PM


      #1

      jkj115 is offline


      Forum Contributor


      Compile error: Expected Array

      Hi — I am getting a «Compile error: Expected Array» for the below code:

      I feel like there is a simple thing I am missing, but can’t figure it out. Any help is appreciated. Thanks

      pls click the star if you liked my answer!


    2. 05-27-2016, 02:41 PM


      #2

      Re: Compile error: Expected Array

      This will compile and run.

      Not sure you need an array though if you just want to put the sheet names in cells.

      If posting code please use code tags, see here.


    3. 05-27-2016, 02:58 PM


      #3

      jkj115 is offline


      Forum Contributor


      Re: Compile error: Expected Array

      Thanks. I wanted to put the values into the array. This worked. Thanks


    4. 05-27-2016, 03:00 PM


      #4

      Re: Compile error: Expected Array

      That code doesn’t put any values in the array.


    5. 05-27-2016, 03:01 PM


      #5

      jkj115 is offline


      Forum Contributor


      Re: Compile error: Expected Array


    INTELLIGENT WORK FORUMS
    FOR COMPUTER PROFESSIONALS

    Contact US

    Thanks. We have received your request and will respond promptly.

    Log In

    Come Join Us!

    Are you a
    Computer / IT professional?
    Join Tek-Tips Forums!

    • Talk With Other Members
    • Be Notified Of Responses
      To Your Posts
    • Keyword Search
    • One-Click Access To Your
      Favorite Forums
    • Automated Signatures
      On Your Posts
    • Best Of All, It’s Free!

    *Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

    Posting Guidelines

    Promoting, selling, recruiting, coursework and thesis posting is forbidden.

    Students Click Here

    Compile error Expected array

    Compile error Expected array

    (OP)

    28 Jan 13 11:18

    When I compile I am getting an expected array error. I have declared the variables so I don’t know why I would be getting this error. The line causing the error is highlighted in blue. I would greatly appreciate any help.

    CODE

    'Module
    
    Public Function GetDataTypeTF(D As Field, ByRef lTbl As Integer, ByRef lRow As Integer, ByRef lFld As Integer, intCol As Integer) As String
    ' **********************************************************************************
    ' *** THIS FUNCTION READS THE FIELDS FROM THE TABLE AND CREATES A REPORT OF IT******
    ' **********************************************************************************
        Dim dBase As DAO.Database
        Dim xlApp As Object
        Dim wbExcel As Object
        Dim fRow As Long
        Set dBase = CurrentDb
        Dim IndexExists As Boolean
        Dim IndexText As String
        Dim idx As DAO.Index
        Dim prp As DAO.Property
        Dim strIdx As DAO.Index
        Dim strCol As String
        Dim strTbl As String
        Dim strFld As String
        Dim ConvColLet As String
        Dim intColCnt As Integer
        With goXL.ActiveSheet
            .Range("A" & lRow) = dBase.TableDefs(lTbl).Fields(lFld).SourceTable
            For intColCnt = 2 To intCol
                strCol = ConvColLet(intColCnt) 
                .Range(strCol & lRow) = dBase.TableDefs(lTbl).Fields(lFld).Name
            Next intCol
        End With
    End Function
    
    
    'Other Function
    
    Public Function ConvColLet(intCol As Integer) As String
    ' ******************************************************************************
    ' *** THIS FUNCTION RETURNS A LETTER FOR A COLUMN NUMBER FOR CELL REFERENCES ***
    ' ******************************************************************************
    'strLeftLetter = ConvColLet(intFirstColumn)
    Select Case intCol
        Case 1
            ConvColLet = "A"
        Case 2
            ConvColLet = "B"
        Case 3
            ConvColLet = "C"
        Case 4
            ConvColLet = "D"
        Case 5
            ConvColLet = "E"
        Case 6
            ConvColLet = "F"
        Case 7
            ConvColLet = "G"
        Case 8
            ConvColLet = "H"
        Case 9
            ConvColLet = "I"
        Case 10
            ConvColLet = "J"
        Case 11
            ConvColLet = "K"
        Case 12
            ConvColLet = "L"
        Case 13
            ConvColLet = "M"
        Case 14
            ConvColLet = "N"
        Case 15
            ConvColLet = "O"
        Case 16
            ConvColLet = "P"
        Case 17
            ConvColLet = "Q"
        Case 18
            ConvColLet = "R"
        Case 19
            ConvColLet = "S"
        Case 20
            ConvColLet = "T"
        Case 21
            ConvColLet = "U"
        Case 22
            ConvColLet = "V"
        Case 23
            ConvColLet = "W"
        Case 24
            ConvColLet = "X"
        Case 25
            ConvColLet = "Y"
        Case 26
            ConvColLet = "Z"
        Case 27
            ConvColLet = "AA"
        Case 28
            ConvColLet = "AB"
        Case 29
            ConvColLet = "AC"
        Case 30
            ConvColLet = "AD"
        Case 31
            ConvColLet = "AE"
        Case 32
            ConvColLet = "AF"
        Case 33
            ConvColLet = "AG"
        Case 34
            ConvColLet = "AH"
        Case 35
            ConvColLet = "AI"
        Case 36
            ConvColLet = "AJ"
        Case 37
            ConvColLet = "AK"
        Case 38
            ConvColLet = "AL"
        Case 39
            ConvColLet = "AM"
        Case 40
            ConvColLet = "AN"
        Case 41
            ConvColLet = "AO"
        Case 42
            ConvColLet = "AP"
        Case 43
            ConvColLet = "AQ"
        Case 44
            ConvColLet = "AR"
        Case 45
            ConvColLet = "AS"
        Case 46
            ConvColLet = "AT"
        Case 47
            ConvColLet = "AU"
        Case 48
            ConvColLet = "AV"
        Case 49
            ConvColLet = "AW"
        Case 50
            ConvColLet = "AX"
        Case 51
            ConvColLet = "AY"
        Case 52
            ConvColLet = "AZ"
        Case 53
            ConvColLet = "BA"
        Case 54
            ConvColLet = "BB"
        Case 55
            ConvColLet = "BC"
        Case 56
            ConvColLet = "BD"
        Case 57
            ConvColLet = "BE"
        Case 58
            ConvColLet = "BF"
        Case 59
            ConvColLet = "BG"
        Case 60
            ConvColLet = "BH"
        Case 61
            ConvColLet = "BI"
        Case 62
            ConvColLet = "BJ"
        Case 63
            ConvColLet = "BK"
        Case 64
            ConvColLet = "BL"
        Case 65
            ConvColLet = "BM"
        Case 66
            ConvColLet = "BN"
        Case 67
            ConvColLet = "BO"
        Case 68
            ConvColLet = "BP"
        Case 69
            ConvColLet = "BQ"
        Case 70
            ConvColLet = "BR"
        Case 71
            ConvColLet = "BS"
        Case 72
            ConvColLet = "BT"
        Case 73
            ConvColLet = "BU"
        Case 74
            ConvColLet = "BV"
        Case 75
            ConvColLet = "BW"
        Case 76
            ConvColLet = "BX"
        Case 77
            ConvColLet = "BY"
        Case 78
            ConvColLet = "BZ"
        Case 79
            ConvColLet = "CA"
        Case 80
            ConvColLet = "CB"
        Case 81
            ConvColLet = "CC"
        Case 82
            ConvColLet = "CD"
        Case 83
            ConvColLet = "CE"
        Case 84
            ConvColLet = "CF"
        Case 85
            ConvColLet = "CG"
        Case 86
            ConvColLet = "CH"
        Case 87
            ConvColLet = "CI"
        Case 88
            ConvColLet = "CJ"
        Case 89
            ConvColLet = "CK"
        Case 90
            ConvColLet = "CL"
        Case 91
            ConvColLet = "CM"
        Case 92
            ConvColLet = "CN"
        Case 93
            ConvColLet = "CO"
        Case 94
            ConvColLet = "CP"
        Case 95
            ConvColLet = "CQ"
        Case 96
            ConvColLet = "CR"
        Case 97
            ConvColLet = "CS"
        Case 98
            ConvColLet = "CT"
        Case 99
            ConvColLet = "CU"
        Case 100
            ConvColLet = "CV"
        Case Else
            ConvColLet = "CZ"
    End Select
    End Function 

    Red Flag Submitted

    Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
    The Tek-Tips staff will check this out and take appropriate action.

    Join Tek-Tips® Today!

    Join your peers on the Internet’s largest technical computer professional community.
    It’s easy to join and it’s free.

    Here’s Why Members Love Tek-Tips Forums:

    • Tek-Tips ForumsTalk To Other Members
    • Notification Of Responses To Questions
    • Favorite Forums One Click Access
    • Keyword Search Of All Posts, And More…

    Register now while it’s still free!

    Already a member? Close this window and log in.

    Join Us             Close

    • Home
    • VBForums
    • Visual Basic
    • Office Development
    • [RESOLVED] Error message «Compile error : Expected array»

    1. Nov 16th, 2017, 08:43 AM


      #1

      hafsarabic is offline

      Thread Starter


      Member


      Resolved [RESOLVED] Error message «Compile error : Expected array»

      Hello experts,
      I’m newbie in VBA. I would like to add a trusted location key to the registry using vba. To do this I’m using the following code. Everytime I run this code it gives me an error message

      Compile error : Expected array»

      for ‘RegKeyExists’

      Code:

      Function RegKeyExists(i_RegKey As String) As Boolean
      Dim myWS As Object
      
        On Error GoTo ErrorHandler
        'access Windows scripting
        Set myWS = CreateObject("WScript.Shell")
        'try to read the registry key
        myWS.RegRead i_RegKey
        'key was found
        RegKeyExists = True
        Exit Function
       
      ErrorHandler:
        'key was not found
        RegKeyExists = False
      End Function
      
      Public Function AddTrustedLocation()
      On Error GoTo err_proc
      'sets registry key for 'trusted location'
      
          Dim intLocns As Integer
          Dim i As Integer
          Dim intNotUsed As Integer
          Dim strLnKey As String
          Dim reg As Object
          Dim strPath As String
          Dim RegKeyExists As String
          
          Set reg = CreateObject("wscript.shell")
          strPath = CurrentProject.Path
          
      If RegKeyExists("HKEY_CURRENT_USERSoftwareMicrosoftOffice12.0AccessSecurityTrusted Locations") = True Then
          strLnKey = "HKEY_CURRENT_USERSoftwareMicrosoftOffice12.0AccessSecurityTrusted LocationsLocation"
      ElseIf RegKeyExists("HKEY_CURRENT_USERSoftwareMicrosoftOffice14.0AccessSecurityTrusted Locations") = True Then
          strLnKey = "HKEY_CURRENT_USERSoftwareMicrosoftOffice14.0AccessSecurityTrusted LocationsLocation"
      ElseIf RegKeyExists("HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0AccessSecurityTrusted Locations") = True Then
          strLnKey = "HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0AccessSecurityTrusted LocationsLocation"
      End If
      
      On Error GoTo err_proc0
          'find top of range of trusted locations references in registry
          For i = 999 To 0 Step -1
              reg.RegRead strLnKey & i & "Path"
              GoTo chckRegPths        'Reg.RegRead successful, location exists > check for path in all locations 0 - i.
      checknext:
          Next
          MsgBox "Unexpected Error - No Registry Locations found", vbExclamation
          Exit Function
          
      chckRegPths:
      'Check if Currentdb path already a trusted location
      'reg.RegRead fails before intlocns = i then is unused location and
      'will be used for new trusted location if path not already in registy
      
      On Error GoTo err_proc1:
          For intLocns = 1 To i
              reg.RegRead strLnKey & intLocns & "Path"
              'If Path already in registry -> exit
              If InStr(1, reg.RegRead(strLnKey & intLocns & "Path"), strPath) = 1 Then GoTo exit_proc
      NextLocn:
          Next
          
          If intLocns = 999 Then
              MsgBox "Location count exceeded - unable to write trusted location to registry", vbInformation
              GoTo exit_proc
          End If
          'if no unused location found then set new location for path
          If intNotUsed = 0 Then intNotUsed = i + 1
          
      On Error GoTo err_proc:
          strLnKey = strLnKey & intNotUsed & ""
          reg.RegWrite strLnKey & "AllowSubfolders", 1, "REG_DWORD"
          reg.RegWrite strLnKey & "Date", Now(), "REG_SZ"
          reg.RegWrite strLnKey & "Description", Application.CurrentProject.Name, "REG_SZ"
          reg.RegWrite strLnKey & "Path", strPath & "", "REG_SZ"
          
      exit_proc:
          Set reg = Nothing
          Exit Function
          
      err_proc0:
          Resume checknext
          
      err_proc1:
          intNotUsed = intLocns
          Resume NextLocn
          
      err_proc:
          MsgBox Err.Description
          Resume exit_proc
          
      End Function

      How can I solve it?

      Abu Hafsa


    2. Nov 16th, 2017, 03:13 PM


      #2

      Re: Error message «Compile error : Expected array»

      remove the line Dim RegKeyExists As String the local variable would override the function of the same name

      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
    • Office Development
    • [RESOLVED] Error message «Compile error : Expected array»


    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 cannot define scripted plugin class
  • Compile error byref argument type mismatch
  • Compile error block if without end if
  • Compile error argument not optional vba
  • Compile error ambiguous name detected