В этой статье представлена ошибка с номером Ошибка 457, известная как Этот ключ уже связан с элементом этой коллекции, описанная как Ключ — это строка, указанная в методе Add, которая однозначно идентифицирует конкретный член коллекции.
О программе Runtime Ошибка 457
Время выполнения Ошибка 457 происходит, когда Windows дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- Добавить — сложение — это математическая операция, которая представляет объединение коллекций объектов в более крупную коллекцию.
- Элемент — в метаданных, термин элемент данных — это атомарная единица данных, которая имеет точное значение или точную семантику.
- Key — уникальный идентификатор, используемый для получения парного значения.
- Член — член — это элемент объекта в парадигме объектно-ориентированного программирования.
- Строка — строка — это конечная последовательность символов, обычно используется для текста, но иногда и для произвольных данных.
- Коллекция . API коллекций предоставляют разработчикам набор классов и интерфейсов, которые упрощают работу с коллекциями объектов.
- Метод . Метод, который часто называют функцией, подпрограммой или процедурой, представляет собой код, который выполняет задачу и связан с классом или объектом.
Симптомы Ошибка 457 — Этот ключ уже связан с элементом этой коллекции
Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Только для примера)
Причины Этот ключ уже связан с элементом этой коллекции — Ошибка 457
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.
Метод 5 — Запустить очистку диска
Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.
- Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
- Вы также можете очистить кеш и перезагрузить компьютер.
- Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C
- Щелкните «Свойства», а затем — «Очистка диска».
Метод 1 — Закройте конфликтующие программы
Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.
- Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
- Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
- Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
- Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.
Метод 2 — Обновите / переустановите конфликтующие программы
Использование панели управления
- В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
- В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
- Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
- В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
- Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.
Использование других методов
- В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
- В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
- Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
- Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.
Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.
Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.
Метод 4 — Переустановите библиотеки времени выполнения
Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.
- Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
- Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
- Загрузите последний распространяемый пакет от Microsoft и установите его.
Метод 6 — Переустановите графический драйвер
Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:
- Откройте диспетчер устройств и найдите драйвер видеокарты.
- Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.
Метод 7 — Ошибка выполнения, связанная с IE
Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:
- Сбросьте настройки браузера.
- В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
- Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
- Отключить отладку скриптов и уведомления об ошибках.
- В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
- Установите флажок в переключателе.
- Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.
Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.
Другие языки:
How to fix Error 457 (This key is already associated with an element of this collection) — A key is a string specified in the Add method that uniquely identifies a specific member of a collection.
Wie beheben Fehler 457 (Dieser Schlüssel ist bereits mit einem Element dieser Sammlung verknüpft) — Ein Schlüssel ist eine in der Add-Methode angegebene Zeichenfolge, die ein bestimmtes Mitglied einer Auflistung eindeutig identifiziert.
Come fissare Errore 457 (Questa chiave è già associata a un elemento di questa raccolta) — Una chiave è una stringa specificata nel metodo Add che identifica in modo univoco un membro specifico di una raccolta.
Hoe maak je Fout 457 (Deze sleutel is al gekoppeld aan een element van deze verzameling) — Een sleutel is een tekenreeks die is opgegeven in de methode Toevoegen en die op unieke wijze een specifiek lid van een verzameling identificeert.
Comment réparer Erreur 457 (Cette clé est déjà associée à un élément de cette collection) — Une clé est une chaîne spécifiée dans la méthode Add qui identifie de manière unique un membre spécifique d’une collection.
어떻게 고치는 지 오류 457 (이 키는 이미 이 컬렉션의 요소와 연결되어 있습니다.) — 키는 컬렉션의 특정 구성원을 고유하게 식별하는 Add 메서드에 지정된 문자열입니다.
Como corrigir o Erro 457 (Esta chave já está associada a um elemento desta coleção) — Uma chave é uma string especificada no método Add que identifica exclusivamente um membro específico de uma coleção.
Hur man åtgärdar Fel 457 (Den här nyckeln är redan associerad med ett element i den här samlingen) — En nyckel är en sträng som anges i metoden Lägg till som unikt identifierar en specifik medlem i en samling.
Jak naprawić Błąd 457 (Ten klucz jest już powiązany z elementem tej kolekcji) — Klucz to ciąg określony w metodzie Add, który jednoznacznie identyfikuje określony element członkowski kolekcji.
Cómo arreglar Error 457 (Esta clave ya está asociada a un elemento de esta colección.) — Una clave es una cadena especificada en el método Add que identifica de forma única a un miembro específico de una colección.
Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.
Следуйте за нами:
Последнее обновление:
28/09/22 11:49 : Пользователь Windows 10 проголосовал за то, что метод восстановления 5 работает для него.
Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.
ШАГ 1:
Нажмите здесь, чтобы скачать и установите средство восстановления Windows.
ШАГ 2:
Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.
ШАГ 3:
Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.
СКАЧАТЬ СЕЙЧАС
Совместимость
Требования
1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.
ID статьи: ACX011708RU
Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000
Error Number: | Runtime Error 457 | |
Error Name: | This key is already associated with an element of this collection | |
Error Description: | A key is a string specified in the Add method that uniquely identifies a specific member of a collection. | |
Developer: | Microsoft Corporation | |
Software: | Windows Operating System | |
Applies to: | Windows XP, Vista, 7, 8, 10, 11 |
Description of This key is already associated with an element of this collection
People often prefer to refer to This key is already associated with an element of this collection as a «runtime error», also known as a software bug. Programmers work through different levels of debugging in attempt to make sure that Windows Operating System is as close to error-free as possible. As with anything in life, sometimes problems like error 457 get overlooked.
The error 457 error — seen as «A key is a string specified in the Add method that uniquely identifies a specific member of a collection.» — might be encountered by Windows Operating System users resulting from normal use of the program. In the event of the detected error 457, customers may convey the presence of problem to Microsoft Corporation via email or bug reporting. Programmers can then correct these errors in the code and include a hotfix that can be downloaded from their website. If there’s a prompt for a Windows Operating System update, it’s usually a workaround for fixing issues like error 457 and other bugs.
What Produces Runtime Error 457?
Execution faults at the startup of Windows Operating System is when you’re most likely to run into This key is already associated with an element of this collection. Here’s the three most common causes why error 457 runtime errors happen:
Error 457 Crash — This is a common error 457 runtime error that results in the program completely terminating. This arises when Windows Operating System fails to function properly, or does not know what output would be suitable.
This key is already associated with an element of this collection Memory Leak — If there’s a memory leak in Windows Operating System, it may cause the OS to appear sluggish. It may be triggered by the misconfiguration of the software by Microsoft Corporation, or when one command starts a loop which can’t be ended.
Error 457 Logic Error — You can experience a logic error when the program produces incorrect results even if the user specifies the right value. Usual causes of this problem are due to faults in data handling.
Typically, This key is already associated with an element of this collection errors are caused by a corrupt or missing Windows Operating System-associated file, sometimes due to malware infection. Downloading and replacing your Microsoft Corporation file can fix the problem in most cases. Moreover, as an overall cleanup and preventive measure, we recommend using a registry cleaner to cleanup any invalid file, Microsoft Corporation file extension, or registry key entries to prevent related error messages.
Classic This key is already associated with an element of this collection Problems
The most common This key is already associated with an element of this collection errors that can appear on a Windows-based computer are:
- «Error in Application: This key is already associated with an element of this collection»
- «Invalid Win32 Program: This key is already associated with an element of this collection»
- «Sorry for the inconvenience — This key is already associated with an element of this collection has a problem.»
- «This key is already associated with an element of this collection can’t be located.»
- «This key is already associated with an element of this collection is missing.»
- «Error starting program: This key is already associated with an element of this collection.»
- «This key is already associated with an element of this collection not executing.»
- «This key is already associated with an element of this collection failed.»
- «Faulting Application Path: This key is already associated with an element of this collection.»
Windows Operating System-involved This key is already associated with an element of this collection issues happen during install, when This key is already associated with an element of this collection-related software is running, startup or shutdown, or during the Windows installation process. Keeping track of when and where your This key is already associated with an element of this collection error occurs is a critical piece of information in troubleshooting the problem.
Epicenters of This key is already associated with an element of this collection Headaches
Windows Operating System and This key is already associated with an element of this collection issues come from missing or corrupt files, Windows registry invalid entries, and malware infections.
Especially, This key is already associated with an element of this collection errors stem from:
- Invalid (corrupt) This key is already associated with an element of this collection registry entry.
- Malware has infected This key is already associated with an element of this collection, creating corruption.
- This key is already associated with an element of this collection maliciously deleted (or mistakenly) by different rogue or valid program.
- Another software application in conflict with This key is already associated with an element of this collection.
- Incomplete or corrupt Windows Operating System (This key is already associated with an element of this collection) from download or installation.
Product by Solvusoft
Download Now
WinThruster 2022 — Scan your PC for computer errors.
Compatible with Windows 11, 10, 8, 7, Vista, XP and 2000
Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall
Problem
Unable to save a Quality Stage RuleSet after making a modification, receiving a run-time error 457.
Symptom
The run-time error 457 is generated after editing and saving a RuleSet, followed by the crash of the DataStage Designer.
When reopening the Designer the modifications are not saved.
Cause
Reference table names defined in the code of the rule must be defined in UPPER case and should begin with an alphabetical character
Diagnosing The Problem
Verify the code of the RuleSet to determine if you the reference table name is defined in upper case and is starting with an alphabetical character.
Resolving The Problem
Change all reference table names which appear in lower case or names that do not begin with an alphabetical character
[{«Product»:{«code»:»SSVSBF»,»label»:»InfoSphere QualityStage»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»—«,»Platform»:[{«code»:»PF002″,»label»:»AIX»},{«code»:»PF033″,»label»:»Windows»},{«code»:»PF016″,»label»:»Linux»},{«code»:»PF027″,»label»:»Solaris»},{«code»:»PF010″,»label»:»HP-UX»}],»Version»:»8.7;8.5.0.2;8.5.0.1;8.5;8.1.0.1;8.1;8.0.2;8.0.1.3;8.0.1.2;8.0.1.1;8.0.1;8.0″,»Edition»:»»,»Line of Business»:{«code»:»»,»label»:»»}}]
Hi there,
I have a Form in my spreadsheet that works with a SQL Server to add information to a Worksheet.
For some reason, whenever I click on the «Get New Orders» button, I get the Run-time error 457: «This key is already associated with an element of this collection.» I have been able to identify the line that it comes up on, I will indicate below.Form Code:[vba]Option Explicit
Private clDataCollection As ScheduleDataCollection ‘ (SQL Query in class module)
Private clNewOrders As ScheduleNewOrdersPrivate Sub UserForm_Initialize()
Set clNewOrders = New ScheduleNewOrders
Me.txtFilterDateStarted.Text = VBA.Format(VBA.DateAdd(«d», -10, Now()), «mm/dd/yyyy»)
End SubPrivate Sub UserForm_Terminate()
Set clNewOrders = Nothing
End SubPrivate Sub cmdAddSelectedOrders_Click()
Dim i As LongFor i = 0 To Me.lstNewOrders.ListCount — 1
If (Me.lstNewOrders.Selected(i) = True) Then
‘ add the isSelected = True to ScheduleData
‘ REMEMBER TO ADD 1 to i BECAUSE IT IS OFFSET BY 1
clDataCollection.Item(i + 1).IsSelected = True
End If
NextclNewOrders.AddSelectedNewOrdersToSchedule
End SubPrivate Sub cmdGetNewOrders_Click()
‘ Check to see if there is a date filter added to the Userform
If (Len(Me.txtFilterDateStarted.Text) > 0) Then
‘ Check if it’s a date
If (IsDate(Me.txtFilterDateStarted.Text) = False) Then
MsgBox «Please enter a valid date in ‘Filter Date Started’.», vbExclamation, «Error»
Exit Sub
Else
‘ Set date filter in NewOrders class
clNewOrders.FilterDateEnteredInFE = CDate(Me.txtFilterDateStarted.Text)
End If
End IfSet clDataCollection = clNewOrders.getNewOrders <——Error Here
If (clDataCollection.Count <= 0) Then Exit Sub
‘ Clear list
Me.lstNewOrders.ClearDim i As Long
‘ Loop through data collection and add orders
lstNewOrders.ColumnCount = 2For i = 1 To clDataCollection.Count
lstNewOrders.AddItem clDataCollection.Item(i).JobCode
lstNewOrders.List(lstNewOrders.ListCount — 1, 1) = clDataCollection.Item(i).LineNumber
Next
End Sub[/vba]
Class Module information; some values and names were replaced with comments or other values:
[vba]Option Explicit‘ This class is designed to update the Production Schedule
Private Const ScheduleSheetName As String = «Production Schedule»
Private Const sSQLFolder As String = «\PATHSQL Queries»
Private Const sFileScheduleCopyPaste As String = Location
Private Const sReplaceDateFilter As String = «@selectDate»
Private dteFilterDateEnteredInFE As DatePrivate colScheduleData As ScheduleDataCollection
Private NAMEDDB As NAMEDSQL‘ Enum for the worksheet to update the columns
Private Enum ScheduleColumns
‘Long list of column names
End Enum»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»’
‘ Filter Date Entered in FE Property
‘ lets the user filter the results based on date entered in FE
»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»’
Public Property Let FilterDateEnteredInFE(ByVal dte As Date)
dteFilterDateEnteredInFE = dte
End Property
Public Property Get FilterDateEnteredInFE() As Date
FilterDateEnteredInFE = dteFilterDateEnteredInFE
End Property»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»’
‘ Schedule Data Collection Property
»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»’
Public Property Get DataCollection() As ScheduleDataCollection
Set DataCollection = colScheduleData
End PropertyPrivate Sub Class_Initialize()
Set SchrothDB = New NAMEDSQL
Set colScheduleData = New ScheduleDataCollection‘ set a standard filter date of 1 month previous
Me.FilterDateEnteredInFE = VBA.DateAdd(«m», -1, Now())
End SubPrivate Sub Class_Terminate()
‘ clean up code
colScheduleData.RemoveAll
Set colScheduleData = NothingSet SchrothDB = Nothing
End SubPublic Function getNewOrders() As ScheduleDataCollection
‘ this procedure uses the SchrothSQL database connection to get a list of orders based on a date
‘ to filter for the results‘ if we ever need to leave the function, it will be set to nothing by default
Set getNewOrders = Nothing‘ Clear collection before setting new values
colScheduleData.RemoveAllDim sSQL As String
sSQL = getTextFromFile(sSQLFolder & sFileScheduleCopyPaste)
If (VBA.Len(sSQL) <= 0) Then Exit Function
sSQL = VBA.Replace(sSQL, sReplaceDateFilter, «‘» & VBA.Format(Me.FilterDateEnteredInFE, «mm/dd/yyyy») & «‘»)
NAMEDDB.OpenConnection
NAMEDDB.executeSQL sSQLSet getNewOrders = processRecordSetForNewOrders(SchrothDB)
NAMEDDB.CloseConnection
End FunctionPrivate Function processRecordSetForNewOrders(ByRef db As SchrothSQL) As ScheduleDataCollection
‘ loops through data and updates the ScheduleDataCollection
If (db.recordSetIsEmpty = True) Then Exit FunctionSet processRecordSetForNewOrders = Nothing
Dim rs As ADODB.RecordSet
Set rs = db.RecordSetIf rs.Fields.Count > 0 Then
Do While Not rs.EOF
Dim d As ScheduleData
Set d = New ScheduleData‘Long list of SQL Query Values
colScheduleData.Add d
rs.MoveNext
Looprs.Close
Set rs = Nothing
Set processRecordSetForNewOrders = colScheduleData
End If
End FunctionPrivate Function IfIsNull(ByRef v As Variant) As String
If (IsNull(v)) Then
IfIsNull = vbNullString
Else
IfIsNull = v
End If
End FunctionPublic Sub AddSelectedNewOrdersToSchedule()
‘ This is used to add new orders selected from user to the schedule at the very end of the data
If (SheetExists(ScheduleSheetName) = False) Then
MsgBox «Cannot find sheet ‘» & ScheduleSheetName & «‘! Terminating program.»
Exit Sub
End IfIf (colScheduleData.Count <= 0) Then Exit Sub
Application.ScreenUpdating = False
Dim i As Long
For i = 1 To colScheduleData.Count
‘ looks for isSelected, then adds it to the schedule
If (colScheduleData.Item(i).IsSelected) Then
Call AddOrderToSchedule(colScheduleData.Item(i))
End If
NextApplication.ScreenUpdating = True
End SubPrivate Sub AddOrderToSchedule(ByRef d As ScheduleData)
‘ this is used to add the order to the worksheet
Dim ScheduleSheet As Excel.Worksheet
Dim NewRow As Long
Dim cf As CellFunctionsSet cf = New CellFunctions
Set ScheduleSheet = ThisWorkbook.Worksheets(ScheduleSheetName)
NewRow = cf.getLastRowInColumn(ScheduleSheet, 1) + 1With ScheduleSheet
‘Long list of cell values
End With ‘ With ScheduleSheetCall AddFormulasToSchedule(ScheduleSheet, NewRow)
End SubPrivate Sub AddFormulasToSchedule(ByRef ws As Excel.Worksheet, ByVal iRow As Long)
‘ using the passed Row value, this adds the necessary formulas to the schedule
‘ Assumes the sheet exists‘ Order Total formula
ws.Cells(iRow, ScheduleColumns.OrderTotal).Formula = _
«=SUM(» _
& ws.Cells(iRow, ScheduleColumns.BeltRevenue).Address(0, 1) _
& «:» _
& ws.Cells(iRow, ScheduleColumns.PlatingRevenue).Address(0, 1) _
& «)»‘ Balance Formula
ws.Cells(iRow, ScheduleColumns.Balance).Formula = _
«=» _
& ws.Cells(iRow, ScheduleColumns.InvoicedAmount).Address(0, 1) _
& «-» _
& ws.Cells(iRow, ScheduleColumns.OrderTotal).Address(0, 1)End Sub
Private Function getDocumentationInfo(ByRef sInfo As String) As String
‘ processes which kind of documentation info to look for in the string
‘ then builds a new string to be added to the production scheduleIf (Len(sInfo) <= 0) Then Exit Function
Dim searchStrings(3, 1) As String
Dim displayString As StringsearchStrings(0, 0) = «VALUE»
searchStrings(0, 1) = «VALUE»
searchStrings(1, 0) = «VALUE»
searchStrings(1, 1) = «VALUE»
searchStrings(2, 0) = «VALUE»
searchStrings(2, 1) = «VALUE»
searchStrings(3, 0) = «VALUE»
searchStrings(3, 1) = «VALUE»Dim i As Long
Dim index As LongFor i = 0 To UBound(searchStrings, 1)
index = InStr(1, sInfo, searchStrings(i, 0), vbTextCompare)
If (index > 0) Then
‘ check if NOT required
If (InStr(1 _
, Mid(sInfo, index, Len(searchStrings(i, 0)) + Len(» not req»)) _
, «Not Req», vbTextCompare) _
<= 0) ThendisplayString = displayString & searchStrings(i, 1) & Chr(10)
End If
End If
Next‘ remove last newline from string
If (Len(displayString) > 0) Then
displayString = Left(displayString, Len(displayString) — 1)
End IfgetDocumentationInfo = displayString
End FunctionPrivate Function SheetExists(ByVal wsName As String) As Boolean
‘ Determines if the specified sheet exists in the workbook
On Error Resume Next
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(wsName)
SheetExists = Not ws Is Nothing
End Function‘ COURTESY OF: http://www.exceluser.com/explore/que…a_textcols.htm
Private Function getTextFromFile(ByRef sFile As String) As StringIf (FileExists(sFile) = False) Then
getTextFromFile = vbNullString
Exit Function
End IfDim nSourceFile As Integer
‘ Close any open text files
Close‘ Get the number of the next free text file
nSourceFile = FreeFile‘ Write the entire file to sText
Open sFile For Input As #nSourceFile
getTextFromFile = VBA.Input$(LOF(1), 1)
Close
End FunctionPrivate Function FileExists(ByRef sFile As String) As Boolean
On Error Resume Next
If Not Dir(sFile, vbDirectory) = vbNullString Then
FileExists = True
Exit Function
End If
On Error GoTo 0
FileExists = False
End Function
[/vba]
If anything is unclear, I have more code I can paste in for anything that may not be defined.
ALFA Пользователь Сообщений: 243 |
#1 13.03.2015 01:35:29 Всем доброй ночи!
но ошибка по прежнему повторяется.. |
||
Doober Пользователь Сообщений: 2141 |
#2 13.03.2015 04:41:49 Можно так проверять.
<#0> |
||
SAS888 Пользователь Сообщений: 757 |
#3 13.03.2015 07:53:10 Вместо
используйте
Чем шире угол зрения, тем он тупее. |
||||
Hugo Пользователь Сообщений: 23137 |
#4 13.03.2015 09:24:34 Не понятно зачем вообще там это всё…
|
||
Казанский Пользователь Сообщений: 8839 |
#5 14.03.2015 14:31:20 ALFA, но ошибка по прежнему повторяется..[/QUOTE]Basic предполагает, что на метке line2 начинается обработчик ошибки. Он должен завершаться оператором Resume или выходом из процедуры. Если в обработчике ошибок возникает ошибка, она уже не обрабатывается *) и происходит останов. Это и происходит у Вас при следующем повторяющемся элементе, т.к. Basic не встретил оператор Resume и считает, что работает обработчик ошибок. Простейший обработчик ошибок должен выглядеть так:
*) Для обработки ошибок в обработчике ошибок можно использовать оператор On Error GoTo -1 |
||
ALFA Пользователь Сообщений: 243 |
#6 18.03.2015 14:48:29 Doober, Ваш вариант успешно подошел, работает, Спасибо!
не подходит, так как если ключ уже существует в коллекции мне необходимо было перейти в определенный участок кода, видимо я привел не совсем подходящий пример( Необходимо было в случае ошибки перейти не к следующему элементу а именно перепрыгнуть на line2: Всем спасибо за предложенные варианты решения! |
||
VBA
Discuss AutoCAD ActiveX and VBA (Visual Basic for Applications) questions here.
Turn on suggestions
Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.
Showing results for
Search instead for
Did you mean:
-
Back to forum -
Previous -
Next
264 Views, 1 Reply
10-29-2002
12:29 AM
Run time error 457 ? help
I am getting run time error 457 while trying to collect attributes from a block anyone know why?
-
Back to forum -
Previous -
Next
1 REPLY 1
10-29-2002
04:17 AM
Post the code and point out the line which is causing the error
—
Veign
www.veign.com
<
> — Bigger, Better, Cleaner!
www.veign.com/download_application.html#Link200
Code Samples & Sample Projects
http://www.veign.com/information/application/info_app.html
Submit Your Best Code (you keep the rights)
http://www.veign.com/information/application/code_submit.html
———
«pechoi» wrote in message
news:f11d352.-1@WebX.maYIadrTaRb…
> I am getting run time error 457 while trying to collect attributes from a
block anyone know why?
-
Back to forum -
Previous -
Next