Run time error 340

Error 340 Control array element 'item' doesn't exist errors can freeze or crash your computer and may lead to possible malware infections. Follow these easy steps to fix your Runtime Errors errors quickly and simply.

This article features error number Code 340, commonly known as Control array element ‘item’ doesn’t exist described as You used an invalid index value to refer to an element in a control array.

About Runtime Code 340

Runtime Code 340 happens when Windows fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.

Definitions (Beta)

Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!

  • Element — In metadata, the term data element is an atomic unit of data that has precise meaning or precise semantics.
  • Control — Use this tag for programming scenarios related to controls interactive elements of the user interface.
  • Array — An array is an ordered data structure consisting of a collection of elements values or variables, each identified by one single dimensional array or vector or multiple indexes

Symptoms of Code 340 — Control array element ‘item’ doesn’t exist

Runtime errors happen without warning. The error message can come up the screen anytime Windows is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.

There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.

Fix Control array element 'item' doesn't exist (Error Code 340)
(For illustrative purposes only)

Causes of Control array element ‘item’ doesn’t exist — Code 340

During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.

Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.

Repair Methods

Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.

If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.

Please note: Neither ErrorVault.com nor it’s writers claim responsibility for the results of the actions taken from employing any of the repair methods listed on this page — you complete these steps at your own risk.

Method 1 — Close Conflicting Programs

When you get a runtime error, keep in mind that it is happening due to programs that are conflicting with each other. The first thing you can do to resolve the problem is to stop these conflicting programs.

  • Open Task Manager by clicking Ctrl-Alt-Del at the same time. This will let you see the list of programs currently running.
  • Go to the Processes tab and stop the programs one by one by highlighting each program and clicking the End Process buttom.
  • You will need to observe if the error message will reoccur each time you stop a process.
  • Once you get to identify which program is causing the error, you may go ahead with the next troubleshooting step, reinstalling the application.

Method 4 — Re-install Runtime Libraries

You might be getting the error because of an update, like the MS Visual C++ package which might not be installed properly or completely. What you can do then is to uninstall the current package and install a fresh copy.

  • Uninstall the package by going to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package.
  • Click Uninstall on top of the list, and when it is done, reboot your computer.
  • Download the latest redistributable package from Microsoft then install it.

Method 2 — Update / Reinstall Conflicting Programs

Using Control Panel

  • For Windows 7, click the Start Button, then click Control panel, then Uninstall a program
  • For Windows 8, click the Start Button, then scroll down and click More Settings, then click Control panel > Uninstall a program.
  • For Windows 10, just type Control Panel on the search box and click the result, then click Uninstall a program
  • Once inside Programs and Features, click the problem program and click Update or Uninstall.
  • If you chose to update, then you will just need to follow the prompt to complete the process, however if you chose to Uninstall, you will follow the prompt to uninstall and then re-download or use the application’s installation disk to reinstall the program.

Using Other Methods

  • For Windows 7, you may find the list of all installed programs when you click Start and scroll your mouse over the list that appear on the tab. You may see on that list utility for uninstalling the program. You may go ahead and uninstall using utilities available in this tab.
  • For Windows 10, you may click Start, then Settings, then choose Apps.
  • Scroll down to see the list of Apps and features installed in your computer.
  • Click the Program which is causing the runtime error, then you may choose to uninstall or click Advanced options to reset the application.

Method 3 — Update your Virus protection program or download and install the latest Windows Update

Virus infection causing runtime error on your computer must immediately be prevented, quarantined or deleted. Make sure you update your virus program and run a thorough scan of the computer or, run Windows update so you can get the latest virus definition and fix.

Method 5 — Run Disk Cleanup

You might also be experiencing runtime error because of a very low free space on your computer.

  • You should consider backing up your files and freeing up space on your hard drive
  • You can also clear your cache and reboot your computer
  • You can also run Disk Cleanup, open your explorer window and right click your main directory (this is usually C: )
  • Click Properties and then click Disk Cleanup

Method 6 — Reinstall Your Graphics Driver

If the error is related to a bad graphics driver, then you may do the following:

  • Open your Device Manager, locate the graphics driver
  • Right click the video card driver then click uninstall, then restart your computer

Method 7 — IE related Runtime Error

If the error you are getting is related to the Internet Explorer, you may do the following:

  1. Reset your browser.
    • For Windows 7, you may click Start, go to Control Panel, then click Internet Options on the left side. Then you can click Advanced tab then click the Reset button.
    • For Windows 8 and 10, you may click search and type Internet Options, then go to Advanced tab and click Reset.
  2. Disable script debugging and error notifications.
    • On the same Internet Options window, you may go to Advanced tab and look for Disable script debugging
    • Put a check mark on the radio button
    • At the same time, uncheck the «Display a Notification about every Script Error» item and then click Apply and OK, then reboot your computer.

If these quick fixes do not work, you can always backup files and run repair reinstall on your computer. However, you can do that later when the solutions listed here did not do the job.

Other languages:

Wie beheben Fehler 340 (Control-Array-Element ‘item’ existiert nicht) — Sie haben einen ungültigen Indexwert verwendet, um auf ein Element in einem Kontrollarray zu verweisen.
Come fissare Errore 340 (L’elemento dell’array di controllo ‘item’ non esiste) — Hai utilizzato un valore di indice non valido per fare riferimento a un elemento in una matrice di controlli.
Hoe maak je Fout 340 (Regelarray-element ‘item’ bestaat niet) — U hebt een ongeldige indexwaarde gebruikt om naar een element in een controlearray te verwijzen.
Comment réparer Erreur 340 (L’élément de tableau de contrôle ‘item’ n’existe pas) — Vous avez utilisé une valeur d’index non valide pour faire référence à un élément dans un tableau de contrôle.
어떻게 고치는 지 오류 340 (제어 배열 요소 ‘item’이(가) 존재하지 않습니다.) — 잘못된 인덱스 값을 사용하여 제어 배열의 요소를 참조했습니다.
Como corrigir o Erro 340 (O elemento da matriz de controle ‘item’ não existe) — Você usou um valor de índice inválido para se referir a um elemento em uma matriz de controle.
Hur man åtgärdar Fel 340 (Kontrollmatriselementet ‘item’ existerar inte) — Du använde ett ogiltigt indexvärde för att referera till ett element i en kontrollmatris.
Как исправить Ошибка 340 (Элемент контрольного массива ‘item’ не существует) — Вы использовали недопустимое значение индекса для ссылки на элемент в массиве элементов управления.
Jak naprawić Błąd 340 (Element tablicy kontrolnej „element” nie istnieje) — Użyłeś nieprawidłowej wartości indeksu, aby odwołać się do elementu w tablicy kontrolnej.
Cómo arreglar Error 340 (El elemento de matriz de control ‘elemento’ no existe) — Usó un valor de índice no válido para hacer referencia a un elemento en una matriz de control.

The Author About The Author: Phil Hart has been a Microsoft Community Contributor since 2010. With a current point score over 100,000, they’ve contributed more than 3000 answers in the Microsoft Support forums and have created almost 200 new help articles in the Technet Wiki.

Follow Us: Facebook Youtube Twitter

Last Updated:

10/01/23 10:16 : A Android user voted that repair method 4 worked for them.

Recommended Repair Tool:

This repair tool can fix common computer problems such as blue screens, crashes and freezes, missing DLL files, as well as repair malware/virus damage and more by replacing damaged and missing system files.

STEP 1:

Click Here to Download and install the Windows repair tool.

STEP 2:

Click on Start Scan and let it analyze your device.

STEP 3:

Click on Repair All to fix all of the issues it detected.

DOWNLOAD NOW

Compatibility

Requirements

1 Ghz CPU, 512 MB RAM, 40 GB HDD
This download offers unlimited scans of your Windows PC for free. Full system repairs start at $19.95.

Article ID: ACX03398EN

Applies To: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Speed Up Tip #22

Reduce The Fonts Loading at Startup:

Having too many fonts can slow down your computer significantly. To avoid this issue, try to trim down the fonts you use by deleting the ones that you don’t use. Don’t forget to backup those fonts in case you decide to use them again.

Click Here for another way to speed up your Windows PC

Microsoft & Windows® logos are registered trademarks of Microsoft. Disclaimer: ErrorVault.com is not affiliated with Microsoft, nor does it claim such affiliation. This page may contain definitions from https://stackoverflow.com/tags under the CC-BY-SA license. The information on this page is provided for informational purposes only. © Copyright 2018

Icon Ex Номер ошибки: Ошибка во время выполнения 340
Название ошибки: Control array element ‘item’ doesn’t exist
Описание ошибки: You used an invalid index value to refer to an element in a control array.
Разработчик: Microsoft Corporation
Программное обеспечение: Windows Operating System
Относится к: Windows XP, Vista, 7, 8, 10, 11

Сводка «Control array element ‘item’ doesn’t exist

Как правило, практикующие ПК и сотрудники службы поддержки знают «Control array element ‘item’ doesn’t exist» как форму «ошибки во время выполнения». Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Windows Operating System. К сожалению, некоторые критические проблемы, такие как ошибка 340, часто могут быть упущены из виду.

Некоторые пользователи могут столкнуться с сообщением «You used an invalid index value to refer to an element in a control array.» при использовании Windows Operating System. Когда это происходит, конечные пользователи программного обеспечения могут сообщить Microsoft Corporation о существовании ошибки 340 ошибок. Затем Microsoft Corporation может исправить эти ошибки в исходном коде и подготовить обновление для загрузки. Следовательно, разработчик будет использовать пакет обновления Windows Operating System для устранения ошибки 340 и любых других сообщений об ошибках.

В чем причина ошибки 340?

Ошибки выполнения при запуске Windows Operating System — это когда вы, скорее всего, столкнетесь с «Control array element ‘item’ doesn’t exist». Мы можем определить, что ошибки во время выполнения ошибки 340 происходят из:

Ошибка 340 Crash — ошибка 340 блокирует любой вход, и это может привести к сбою машины. Если данный ввод недействителен или не соответствует ожидаемому формату, Windows Operating System (или OS) завершается неудачей.

Утечка памяти «Control array element ‘item’ doesn’t exist» — ошибка 340 утечка памяти приводит к тому, что Windows Operating System использует все больше памяти, что делает ваш компьютер запуск медленнее и замедляет вывод системы. Возможные провокации включают отсутствие девыделения памяти и ссылку на плохой код, такой как бесконечные циклы.

Ошибка 340 Logic Error — Логическая ошибка вызывает неправильный вывод, даже если пользователь дал действительные входные данные. Виновником в этом случае обычно является недостаток в исходном коде Microsoft Corporation, который неправильно обрабатывает ввод.

Такие проблемы Control array element ‘item’ doesn’t exist обычно вызваны повреждением файла, связанного с Windows Operating System, или, в некоторых случаях, его случайным или намеренным удалением. Как правило, решить проблему позволяет получение новой копии файла Microsoft Corporation, которая не содержит вирусов. Более того, поддержание чистоты реестра и его оптимизация позволит предотвратить указание неверного пути к файлу (например Control array element ‘item’ doesn’t exist) и ссылок на расширения файлов. По этой причине мы рекомендуем регулярно выполнять очистку сканирования реестра.

Распространенные сообщения об ошибках в Control array element ‘item’ doesn’t exist

Типичные ошибки Control array element ‘item’ doesn’t exist, возникающие в Windows Operating System для Windows:

  • «Ошибка программы Control array element ‘item’ doesn’t exist. «
  • «Недопустимый файл Control array element ‘item’ doesn’t exist. «
  • «Control array element ‘item’ doesn’t exist столкнулся с проблемой и закроется. «
  • «Не удается найти Control array element ‘item’ doesn’t exist»
  • «Отсутствует файл Control array element ‘item’ doesn’t exist.»
  • «Ошибка запуска программы: Control array element ‘item’ doesn’t exist.»
  • «Не удается запустить Control array element ‘item’ doesn’t exist. «
  • «Ошибка Control array element ‘item’ doesn’t exist. «
  • «Control array element ‘item’ doesn’t exist: путь приложения является ошибкой. «

Ошибки Control array element ‘item’ doesn’t exist EXE возникают во время установки Windows Operating System, при запуске приложений, связанных с Control array element ‘item’ doesn’t exist (Windows Operating System), во время запуска или завершения работы или во время установки ОС Windows. Запись ошибок Control array element ‘item’ doesn’t exist внутри Windows Operating System имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.

Эпицентры Control array element ‘item’ doesn’t exist Головные боли

Заражение вредоносными программами, недопустимые записи реестра Windows Operating System или отсутствующие или поврежденные файлы Control array element ‘item’ doesn’t exist могут создать эти ошибки Control array element ‘item’ doesn’t exist.

В основном, осложнения Control array element ‘item’ doesn’t exist связаны с:

  • Недопустимая или поврежденная запись Control array element ‘item’ doesn’t exist.
  • Загрязненный вирусом и поврежденный Control array element ‘item’ doesn’t exist.
  • Control array element ‘item’ doesn’t exist ошибочно удален или злонамеренно программным обеспечением, не связанным с приложением Windows Operating System.
  • Control array element ‘item’ doesn’t exist конфликтует с другой программой (общим файлом).
  • Поврежденная установка или загрузка Windows Operating System (Control array element ‘item’ doesn’t exist).

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Run-Time error 340?

  1. Mar 28th, 2015, 10:46 AM


    #1

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Run-Time error 340?

    So in my program i’m attempting to have a control array of command buttons originally disabled, have the user perform an action enabling the command buttons. when the user clicks the command buttons the go invisible. the form with these buttons is then unloaded and reloaded resetting the command buttons to their original state( visible and disabled) except that when the form is reloaded and the user attempts to enable the buttons again i get a runtime error 340 for the last button that was clicked prior to unloading the form (sometimes the button itself still works but is wiped blank ie caption and colour erased) does anyone know what the cause of this error is and how it can be fixed? Thanks.


  2. Mar 28th, 2015, 10:50 AM


    #2

    Re: Run-Time error 340?

    Without us having to go google error 340? What is error 340?

    Welcome to the forums


  3. Mar 28th, 2015, 10:58 AM


    #3

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    thanks, sorry i thought i put that in there its Run time error: Control array element ‘item’ doesn’t exist


  4. Mar 28th, 2015, 11:04 AM


    #4

    Re: Run-Time error 340?

    Without seeing your code that unloads/loads the array, my gut feeling is that you can’t unload a control that is currently being executed? If that is the case, a timer may work.

    1. Add timer to the form, set it’s Enabled property to True and interval small, say 100
    2. When the user clicks the button, change Timer’s Enabled property to True
    3. In the timer’s Timer event, disable the timer & unload/reload controls

    The idea is that the short delay will allow the button to finish. If that doesn’t work, we’ll need to see some code


  5. Mar 28th, 2015, 11:05 AM


    #5

    Re: Run-Time error 340?

    Count the number of command buttons you have in your array….then debug your program to see what the value that is being used in trying to make visible and disabled. If you have an array of 8 buttons, your upper limit of that array will be 7 (assuming you did not change from the default, starting with command1(0). I just assume the value you are trying to use to make your buttons visible again is one more than in the upperbound value of your array.


  6. Mar 28th, 2015, 11:10 AM


    #6

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    not that didnt work im afraid. the control array is re-enabled like this (its original state being disabled)

    For index = 0 To 25

    cmdLetters(index).Enabled = True

    Next index


  7. Mar 28th, 2015, 11:12 AM


    #7

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    btw there are 26 buttons in the control array


  8. Mar 28th, 2015, 11:12 AM


    #8

    Re: Run-Time error 340?

    If your array is contiguous (no elements are skipped) then this is probably what you want

    Code:

    For index = 0 To cmdLetters.Ubound

    If cmdLetters.UBound is < 25 then you have another problem. What is the value of Index when the error occurs?


  9. Mar 28th, 2015, 11:20 AM


    #9

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    its always equal to the button clicked last prior to original unloading of the form all the others work fine its just the one clicked last


  10. Mar 28th, 2015, 11:24 AM


    #10

    Re: Run-Time error 340?

    And that timer solution didn’t work? Let us see some of your code, specifically the routine that loads/unloads the array

    When you post your code, please enclose it between these two tags so it is easier to read: [code] [/code]


  11. Mar 28th, 2015, 11:29 AM


    #11

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    im not sure what you mean by that the array isnt loaded or unloaded at all its state is just changed between visible and invisible. disabled/enabled .should i be loading this somehow i dont really know


  12. Mar 28th, 2015, 11:34 AM


    #12

    Re: Run-Time error 340?

    Ok, I thought you were loading the buttons at runtime, dynamically. Then let us see the code the unloads/reloads the form. It might just be 2 lines of code, but just to be sure, let’s see that click event


  13. Mar 28th, 2015, 11:42 AM


    #13

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    Code:

    unload frmGame  
    frmGame.show


  14. Mar 28th, 2015, 11:47 AM


    #14

    Re: Run-Time error 340?

    lol, that’s what I was afraid of and I should’ve been more specific. That’s everything that happens in that click event? Then what happens in the form’s Load event? Where is the code that enables/disables the buttons and what does that code look like. Put yourself in our place… We have no idea how your code is written, how events call to other routines, etc. Give us as much as you can so we can visualize the process.

    Personally, I don’t think I’ve ever seen an error that the array item didn’t exist when the control actually existed. And I’m still leaning towards the button’s click event not fully being executed from mouse down to mouse up is the heart of the problem.


  15. Mar 28th, 2015, 11:54 AM


    #15

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    sorry is this any better

    frmMenu

    frmGame

    Code:

    For index = 0 To 25
    cmdLetters(index).Enabled = True
    Next index
    
    unload frmGame

    thats all the code where the control array is being manipulated really i dont know what else i can show you


  16. Mar 28th, 2015, 11:55 AM


    #16

    Re: Run-Time error 340?

    Where is that code located? Form_Load, somewhere else?


  17. Mar 28th, 2015, 11:59 AM


    #17

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    the first one is in frmMenu and the second one is in frmGame


  18. Mar 28th, 2015, 12:02 PM


    #18

    Re: Run-Time error 340?

    Ok, but what event is the code from? Private Sub Form_Load() or somewhere else? Understand what I’m asking?


  19. Mar 28th, 2015, 12:14 PM


    #19

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    first one:

    Code:

    Private Sub cmdPlay_(click)

    Second one:

    Code:

    Private Sub cmdBegin

    the idea is that frmGame is unloaded displaying frmMenu which is still open as it is the form that opens when the program is run. when you click cmd Play it opens frmGame. So the control array is in frmGame and its all disabled, the array is enabled when you click cmdBegin. induvidial command buttons in the array are set to invisible after they are clicked then when the game ends frmGame is unloaded displaying frmMenu (since it was already there). the user can then click cmdPlay again to play another game except that when frmGame is reloaded and they click cmdBegin to enable the array (which should be disabled at this point since frmGame has been unloaded and reloaded as the control array is disabled in the form design) it gives the error when it tries to enable the last command button that was clicked


  20. Mar 28th, 2015, 12:30 PM


    #20

    Re: Run-Time error 340?

    A couple questions

    1. cmdBegin is in frmGame?
    2. If so, why unload the form and reload it? Why not just Enable the buttons

    To try to replicate the scenario, I did this based on what I understand from your post
    1. Created a frmMenu that (for simplicity) has a button that when clicked calls frmGame.Show
    2. Created a frmGame that has an array of 26 disabled buttons + another enabled button: cmdBegin
    3. When cmdBegin is clicked, I have this code. This would not re-enable the buttons because once form is reloaded, doesn’t matter what the enabled state of buttons was before it was reloaded and you say they are default to false so they will be false once reloaded

    Code:

        Dim index As Long
        For index = 0 To 25
            cmdLetters(Index).Enabled = True
        Next
        Unload frmGame 
        frmGame.Show

    4. Moving the unload/show lines of code before the loop does re-enable the buttons

    If my logic isn’t similar to how you described yours, then I apologize as I’m not following. In either case, I cannot replicate Error 340


  21. Mar 28th, 2015, 12:39 PM


    #21

    sdfsfdvvfv is offline

    Thread Starter


    New Member


    Re: Run-Time error 340?

    Im not really sure i can properly communicate exactly how this works because im not all that sure for myself. i think ill just keep trying to fix this myself thank you for your help and time


  22. Mar 28th, 2015, 01:06 PM


    #22

    Re: Run-Time error 340?

    This may help? Typically, games do not unload/reload forms to begin a new game. They usually have a separate subroutine that sets up the game/board. All the code needed to setup the game is contained in that subroutine and/or calls other needed routines from within that subroutine. Then when a new game is about to be played, that subroutine is called. It is generally called from the Form_Load event so the game is initialized when the form first loads. Then as needed, it may be called from other places from within the same form, like a «New Game» button/menu or a message box that appears after a game has been lost/won that asks, «Play Again».

    The simple idea is to have one place that is called to initialize the game.


  23. Mar 28th, 2015, 02:30 PM


    #23

    Re: Run-Time error 340?

    imho, the only way that is possible is
    1)an array of controls created at runtime, and an element is unloaded
    or
    2)an array of controls created at design time
    then delete an array element at design time


  24. Mar 28th, 2015, 02:34 PM


    #24

    Re: Run-Time error 340?

    Quote Originally Posted by IkkeEnGij
    View Post

    imho, the only way that is possible is
    1)an array of controls created at runtime, and an element is unloaded
    or
    2)an array of controls created at design time
    then delete an array element at design time

    Yep, that’s why I was confused also. My guess is that the OP is trying to modify code not written by him because of that comment that he didn’t know exactly how the code works. And if that is the case, it is likely the controls are loaded at runtime

    Last edited by LaVolpe; Mar 28th, 2015 at 02:45 PM.


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Run-Time error 340?


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

nnn

1

31.08.2006, 13:08. Показов 5788. Ответов 15


Имеется массив элементов А(I). Пользователь может удалить любой элемент из этого массива. Нужно после операции удаления отсортировать этот массив, но в цикле по I при достижении индекса удалённого элемента появляется ошибка RunTime Error 340 Control array element ‘item’ doesn’t exist. Можно ли каким-либо образом удалённый элемент не рассматривать, чтобы обойти данную ошибку?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 14:42

2

код в студию.



0



nnn

31.08.2006, 14:59

3

Имеется две формы. На одной из них (PerZZ) — CommandButton’s, а в качестве рисунков на них — элементы ActiveX. На другую форму (Titul) при нажатии соответствующей кнопки на PerZZ должен переноситься соответствующий элемент ActiveX. При этом кнопка на PerZZ становится неактивной.
При удалении ActiveX-а с Titul-а кнопка должна становиться активной. Но нужна проверка. Её и пытаюсь реализовать…

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    If Titul.TitPerZZ.Count > 1 Then
    
        For I = 1 To Titul.TitPerZZ.Count - 1
                 
                If Titul.TitPerZZ(I).Visible = True Then 'здесь выдаёт ошибку
                    For J = LBound(PZZ) To UBound(PZZ)
                        If PerZZ1(J + 1).NumberZN = Titul.TitPerZZ(I).NumberZN Then
                            PerZZ1(J + 1).Enabled = False
                            Command1(J + 1).Enabled = False
                        End If
                    Next J
                End If
           
        Next I
    End If

2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 15:13

4

Скинь на mailto:alexey@vbrussian.com alexey@vbrussian.com исходник.
По всей видимости, достаточно проверять на IsNothing.



0



nnn

31.08.2006, 16:33

5

Что-то у меня в VB v.6 нет такой функции — IsNothing — ошибку выдаёт «Sub или Function не определены».
Исходник — большой, всё в разных местах понапихано, не знаю, как прислать.

2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 16:41

6

Открой Object Browser и посмотри функции, начинающиеся на Is. IsNull, IsEmpty и т.д.
А еще, не ленись, погугли. Там много на эту тему.



0



nnn

31.08.2006, 17:40

7

Нашли текст функции isNothing. Всё равно, не работает. Ту же 340-ю ошибку выдаёт.
Единственное, что могу сказать, удаление элемента с Titul-a сделано через Unload…

Alexey Spirin

2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 18:06

8

Как я понимаю, у вас ситуация, покажая на эту:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Private Sub Command2_Click()
Dim a(1 To 3)
Dim i As Integer
For i = 1 To 3
    Load Command1(i)
    Command1(i).Top = 0
    Command1(i).Left = i * Command1(i).Width
    Command1(i).Caption = "Button " & i
    Command1(i).Visible = True
Next
End Sub
Private Sub Command3_Click()
MsgBox Command1(2).Caption
Unload Command1(2)
MsgBox Command1(2).Caption
End Sub

Предпоследняя строка вызовет вашу ошибку.
Самый простой вариант — сделать отлов ошибки при помощи On Error. Или написать функцию, которая опять же через On Error будет проверять. Вот здесь наглядный тому пример:
http://bbs.vbstreets.ru/viewtopic.php?p=61949 http://bbs.vbstreets.ru/viewtopic.php?p=61949



0



nnn

31.08.2006, 18:14

9

По поводу функции IsNothing: в vb6 такой нет, в инете нашли:

Visual Basic
1
2
3
4
5
Public Function IsNothing(pvar As Variant)
    On Error Resume Next 'Handle errors here
    IsNothing = (pvar Is Nothing)
    On Error GoTo 0 'Reset error handling
End Function

Т.е. отлов ошибки через «On error» как бы происходит. Только положительного результата нет… Вот.

2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 18:30

10

Почитайте, наконец, ссылку, которую я Вам дал.
Там четко описано и про Is Nothing и про требуемую функцию.



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

31.08.2006, 18:36

11

nnn,
На самом деле синтаксис неверен. Нужно Is Nothing. Например:
If ТвойКонтрол Is Nothing Then
VladConn
A, я смотрю, в чьей-то ф-ции IsNothing есть пример верного использования Is Nothing.



0



2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 18:41

12

VladConn, в данном случае ты не прав.
Дело в том, что конструкция Is Nothing даже для выгруженных контролов в Control Array’e возвращает False. Посмотри ссылку.



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

31.08.2006, 19:34

13

Почему это я неправ? По-моему, Alexey Spirin рекомендовал Is Nothing, причем без пробела, на что (и только на это) было обращено мое внимание, поскольку отсутствие пробела повело, судя по-всему, спрашивающего по совсем ложному пути.
;0))



0



2 / 2 / 1

Регистрация: 18.10.2007

Сообщений: 1,749

31.08.2006, 19:51

14

Виноват-виноват, пробел просутил, не спорю)
Однако в данном случае все равно дело не в Is Nothing. Is Nothing в данном случае не подходит. Просто изначально понятно не было, о каком именно случае идет речь.



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

31.08.2006, 20:25

15

Да, конечно.
Я сейчас в отпуске, так что активно не буду наверно участвовать.
VladConn



0



WitC

07.10.2006, 23:51

16

UBound(arrayname[, dimension]) — Возвращает число Long, содержащее максимально возможный индекс массива arrayname указанной размерности. Если вам не всё понятно, то смотрите пример.
Пример:
DimUpper

Visual Basic
1
2
3
4
5
Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Объявляем массивы
Dim AnyArray(10)
Upper = UBound(MyArray, 1) ' Возвратит 10.
Upper = UBound(MyArray, 3) ' Возвратит 20.
Upper = UBound(AnyArray) ' Возвратит 10.

Т.е.

Visual Basic
1
2
3
4
5
6
7
dim a as integer 
...
for i=1 to UBound(MyArray)
     a=a+1
next i
text1.text=a
...
  • Remove From My Forums
  • Question

  • I am getting  Runtime Error 340- Control Array Element «0) does not exist, while executing the VB6 code for Sample Statistics.

    I have created 5 labels «Random Data Sample», «Average», «Standard Deviation», «DataMin» and «DataMax» with Index property as 1, 0, 1,2, 3 respectively and also created  5 list boxes i.e. List1, List2, List3, List4 and List5 respectively for the
    above labels with the code as under :

    Function ArrayStats(DataArray() As Double) As Double()
    Dim Res(4) As Double
         Sum = 0
         SumSquares = 0
         DCount = 0
         DataMin = 999999
         DataMax = 999999
         For i = LBound(DataArray) To UBound(DataArray)
              Sum = Sum + DataArray(i)
              SumSquares = SumSquares + DataArray(i) ^ 2
              If DataArray(i) > DataMax Then DataMax = DataArray(i)
              If DataArray(i) < DataMin Then DataMin = DataArray(i)
              DCount = DCount + 1
        Next
        Avg = Sum / DCount
        StdDev = Sqr(SumSquares / DCount - Avg ^ 2)
        Res(1) = Avg
        Res(2) = StdDev
        Res(3) = DataMin
        Res(4) = DataMax
        ArrayStats = Res()
        End Function
        
    Private Sub Command1_Click()
    Dim SData(100) As Double
    Dim Stats() As Double
    
         List1.Clear
         For i = 1 To 100
               SData(i) = Rnd() * 10000
               List1.AddItem SData(i)
          Next
          Stats() = ArrayStats(SData())
          For i = 1 To 4
                  lblSTATS(i - 1).Caption = Stats(i)
          Next
    End Sub
    

    Pl. help in resolving the problem.

    • Moved by

      Thursday, November 22, 2012 6:47 AM
      (From:Visual Basic General)

Windows 10: run-time error ‘340’ Control array element ’80’ doesn’t exist

Discus and support run-time error ‘340’ Control array element ’80’ doesn’t exist in Windows 10 Customization to solve the problem; How do I fix run-time error ‘340’ Control array ’80’ doesn’t exist in Windows 10?…
Discussion in ‘Windows 10 Customization’ started by fixeditonce, Oct 14, 2018.

  1. run-time error ‘340’ Control array element ’80’ doesn’t exist

    How do I fix run-time error ‘340’ Control array ’80’ doesn’t exist in Windows 10?

    :)

  2. Microsoft Teredo Tunelling Adapter doesn´t exist

    My teredo tunneling adapter is non-existant on my pc, I´ve tried adding it by legacy hardware but it wasn´t there, I’ve set DisabledComponents to 0, it doesn´t show up when i view hidden devices and there´s no download for this driver apparently, I´ve
    tried a lot of solutions and nothing has worked for me.

    Please help me, i can´t play multiplayer games with my friends and neither use party chat on the Xbox App.

  3. hd6950 to hd 6970

    ok
    i ve tried everything:with atiflash from dos,winflash.step by step with bios powercolor hd 6970 from the database.
    nothing,doesn´t work.any suggestion????

  4. run-time error ‘340’ Control array element ’80’ doesn’t exist

    my 3Dprinter doesn´t appear

    My 3D printer doesn´t appear on when I open 3D builder on the left popup to choose printer.

    Is it need to do any previous step?? I thought It was plug and play. the printer is an UP Plus2 from Tiertime so, it is one of the recommended partners manufaturers. any message of error just doesnçt possible to send the prin.

Thema:

run-time error ‘340’ Control array element ’80’ doesn’t exist

  1. run-time error ‘340’ Control array element ’80’ doesn’t exist — Similar Threads — run error ‘340’

  2. BSOD — BugcheckCode 340

    in Windows 10 Gaming

    BSOD — BugcheckCode 340: Hello,My computer crashes sporadically all of a sudden.Can someone help me to solve why this is happening ? Latest DUMP file can be found here.Thanks in advance for any tips….
  3. BSOD — BugcheckCode 340

    in Windows 10 Software and Apps

    BSOD — BugcheckCode 340: Hello,My computer crashes sporadically all of a sudden.Can someone help me to solve why this is happening ? Latest DUMP file can be found here.Thanks in advance for any tips….
  4. there an error that says that my drive doesn’t exist

    in Windows 10 Gaming

    there an error that says that my drive doesn’t exist: I was updating an app on my computer but it won’t let, it says the drive does not exist or is not accessible. I have an external drive were everything is stored and has always worked but not this message appears and i don’t know what to do. And my external hard drive seems to…
  5. there an error that says that my drive doesn’t exist

    in Windows 10 Software and Apps

    there an error that says that my drive doesn’t exist: I was updating an app on my computer but it won’t let, it says the drive does not exist or is not accessible. I have an external drive were everything is stored and has always worked but not this message appears and i don’t know what to do. And my external hard drive seems to…
  6. Port 80 and Port 443 non existent

    in Windows 10 Network and Sharing

    Port 80 and Port 443 non existent: I am trying to use apache for a web development class and we are required to use xmapp to do so, Apache runs on port 80 and I believe SQL runs on port 443 but when i check netstat these ports are not even listed. Nothing I can tell is assigned to these ports either I do not…
  7. BSOD — BugcheckCode 340

    in Windows 10 BSOD Crashes and Debugging

    BSOD — BugcheckCode 340: Hi,

    Since about a week ago, my computer has been having random BSOD’s and I can’t really wrap my head around it.
    It happens when I’m playing games, but also when randomly browsing the internet.

    I’ve uploaded the minidumps from the last 2 files to a Onedrive which you can…

  8. Keyset doesn’t exist

    in Windows Hello & Lockscreen

    Keyset doesn’t exist: I reset my password two days or so ago and then when I was trying to figure out an issue with Skype saying my pin was an issue, I discovered that my account on my Microsoft computer stated that I needed to verify my identity. When I tried to do that, it gave me an error…
  9. BSOD — BugcheckCode 340

    in Windows 10 BSOD Crashes and Debugging

    BSOD — BugcheckCode 340: Hi, can someone help me to solve why is my computer crashing all of a sudden?

    I didn’t make any HW changes or install anything new but from 25.9. it keeps crashing a I don’t know why.

    I tried few HDD test and every pass.

    Log from event viewer can be found here

    Thanks…

  10. Cannot run Photoshop Elements

    in Microsoft Windows 10 Store

    Cannot run Photoshop Elements: I cannot run Photoshop Elements 2018 that I’ve bought at the Windows Store. I receive the message that there isn’t enough Ram and I have to select the integer between 50-to 8. I tried regedit but I found the software and Adobe but not Photoshop window…

Users found this page by searching for:

  1. run-time error 340 control array 80

    ,

  2. run-time error 340

    ,

  3. run time error 340


Windows 10 Forums

How to fix the Code 340 (SOLVED)

System Information:

Your PC is currently running:  

special offer

Code 340 can often appear due to incorrectly configured system settings or through violations of the Windows registry. This error is relatively quick and easy to fix if you use PC Repair, configured to solve all common registry problems.

  • Error name: Code 340
  • Applies to: Windows 10, 11, 8, 7, Vista, XP
  • Code 340 is appearing and starting to break a window of the active program;
  • Code 340 appears on the screen;
  • The message ‘A problem has been detected, and Windows has been shut down to prevent damage to your computer. The problem seems to be caused by the following file…’;
  • The user’s computer stops working, showing a Code 340 error while starting the program;
  • Windows is functioning poorly, responding slowly to commands;
  • The user’s PC hangs frequently

Code 340 error messages can appear due to a clogged Windows registry and erroneous entries of non-existent programs because the user usually removes software incorrectly. Other common causes are incorrect data entry, missing files that were accidentally deleted from the registry, causing problems with the system.

  1. 1. Download PC Repair.
  2. 2. Install and run the program.
  3. 3. Press Scan Now to detect errors and different deviations from the optimal level.
  4. 4. Press Repair All to fix each problem.


This page is available in other languages:
Deutsch |
Español |
Italiano |
Français |
Indonesia |
Nederlands |
Nynorsk |
Português |
Русский |
Українська |
Türkçe |
Malay |
Dansk |
Polski |
Română |
Suomi |
Svenska |
Tiếng việt |
Čeština |
العربية |
ไทย |
日本語 |
简体中文 |
한국어

Понравилась статья? Поделить с друзьями:
  • Run time error 339 component mscomctl ocx как исправить windows 10
  • Run time error 339 component mscomctl ocx or one of its dependencies not
  • Run time error 339 component mscomct2 ocx как исправить
  • Run time error 339 component comdlg32 ocx как исправить
  • Run time error 339 comctl32 ocx