Subscript out of range vba excel
Excel VBA «Subscript out of range» Ошибка Запуска ‘9’
Я попытался реализовать следующий код, чтобы я мог прочитать значение ячейки, а затем поместить это значение в другую ячейку на том же листе.
Рабочий лист имеет следующее имя: TestUserGuidance (без пробелов) Код выглядит следующим образом:
Может кто-нибудь посоветовать, где я ошибаюсь?
3 Ответа
Я думаю, что vba не может найти лист TestUserGuidance. Если я запускаю следующее В окне immediate, я получаю ошибку «Object doesn’t support this property or method»:
Если я запускаю это, я получаю ошибку, которую вы упоминаете «индекс вне диапазона»:
Это говорит мне о том, что активная книга неверна, так как вы получили бы другую ошибку, если бы vba смог найти рабочий лист. Можете ли вы попробовать добавить ThisWorkbook (а также использовать диапазон)?
Другой вариант-переименовать рабочий лист:
Тогда вам не придется беспокоиться об активной книге (а также получить intellisence):
Кроме того, я бы предложил вам внести все исправления, предложенные другими. В противном случае у вас, скорее всего, возникнут другие проблемы.
Наконец, если рабочий лист похож на шаблон, и структура не изменится, вам будет лучше просто использовать формулу (т. е. формулу E1: =B1). Даже если есть условная логика, ее легче поддерживать в виде формулы, а не кода vba.
Вот некоторые шаги по устранению неполадок:
Переключите точку останова на линии, где задано значение dblPower, щелкнув по серой области слева:
Также откройте окно немедленного доступа, если его еще нет, нажав ctrl+g:
При запуске кода он должен остановиться в точке останова. Теперь вы можете проверить, что находится в области видимости. Попробуйте ввести следующее В окне немедленного ввода и нажмите клавишу Ввод:
Обратите внимание, что вы также можете шагать по строке кода, нажимая клавишу F8, когда курсор находится где-то внутри подпрограммы. Суть в том, что вам может потребоваться изучить код строка за строкой, чтобы понять это.
Это способ заставить ваш код работать:
При использовании «E1» или «B1» следует использовать Range , а не ячейки. В моем ответе Worksheets(1) относится к Worksheets(«TestUserGuidance») .
Только dblRoadSpeed объявляется как double. Чтобы исправить это, объявите все свои переменные как индивидуальные, в vba вы можете сделать это двумя способами.
Кроме того, вам не нужно объявлять какую-либо переменную, чтобы делать то, что вы делаете. Вы можете скопировать значение в один шаг.
Похожие вопросы:
Я пытался обернуть свою голову вокруг использования циклов и массивов и собрал приведенный ниже пример, который берет имена листов из таблицы на листе и сохраняет их в массиве, из которого.
Я попытался получить вывод следующего кода, но его выдает Ошибка Ниже приведен код: Dim strRisk() As String Dim riskLen As Integer strRisk = SplitMultiDelims(ActiveCell.Offset(0, 9).Value, @) MsgBox.
Я пытаюсь использовать VBA, чтобы открыть гиперссылки из моего excel, используя следующий код: numRow = 1 Do While WorksheetFunction.IsText(Range(E & numRow)) ActiveSheet.Range(E &.
Я новичок в Excel VBA и начал создавать книгу отслеживания времени для обучения. Частью этого является цикл For, который должен добавлять один именованный лист для каждого месяца в году: Sub.
В моей программе, если field_to_split содержит пустую строку, то я получаю следующую ошибку: Run-time error ‘9’: Subscript out of range Как временный fix, я добавил в On Error Resume Next , потому.
Private Sub Worksheet_Change(ByVal Target As Range) Dim b As Integer b = 0 Dim cell As Range Dim rgn As Range Set rgn = Range(f2:f200) For Each cell In rgn If IsEmpty(cell) = False Then b = b + 1.
Я наткнулся на ошибку, которую, похоже, не могу решить после нескольких часов поиска в интернете подобных ошибок, которых я нашел дюжину, но они, похоже, не вписываются в эту ситуацию. Установка.
Я пытаюсь заполнить массив Hrs значениями, обусловленными тем, являются ли определенные ячейки пустыми или нет: Sub Add_training_hrs() Dim Rng1, Rng2 As Range Dim m, n As Integer Dim Hrs() As Double.
Я новичок в VBA Excel. Я пытаюсь сравнить ячейки из двух разных листов, и если они одинаковы, мне нужно выполнить расчет, как показано ниже. Проблема в том, что при запуске я получаю Run-Time error.
у меня есть некоторый код, который я написал, используя вектор 2d вместо массива 2d, однако когда я иду, чтобы запустить его, все, что он говорит, — это vector subscript out of range. любая помощь.
Run Time Error 9: Subscript out of range. Find Method
when the code runs until
- ‘*This is to the row that contani the target
- lRow = Worksheets(«sheet3»).Range(«A3:A3000»).Find(What:=code, LookIn:=xlValues, _
- LookAt:=xlPart, _
- SearchOrder:=xlByColumns, _
- SearchDirection:=xlNext, _
- MatchCase:=False, _
- SearchFormat:=False).Row
it gives me this msg : subscribpt out of range
any idea why . Thank u
here is the whole code:
- Private Sub Worksheet_Change(ByVal Target As Range)
- Dim code As Variant
- Dim lRow As Long
- Dim color As Range
- Dim discrib As Range
- Dim price As Range
- Dim myrange As Range
- Set myrange = Sheet7.Range(«C6»)
- If Intersect(Target, myrange) Is Nothing Then
- Exit Sub
- Else
- code = Target
- ‘*This is to the row that contani the target
- lRow = Worksheets(«sheet3»).Range(«A3:A3000»).Find(What:=code, LookIn:=xlValues, _
- LookAt:=xlPart, _
- SearchOrder:=xlByColumns, _
- SearchDirection:=xlNext, _
- MatchCase:=False, _
- SearchFormat:=False).Row
- Set discrib = Sheet3.Range(«A1»).Offset(lRow, 1).Value
- Set color = Sheet3.Range(«A1»).Offset(lRow, 4).Value
- Set price = Sheet3.Range(«A1»).Offset(lRow, 9).Value
- Sheet7.Range(«C7»).Value = discrib
- Sheet7.Range(«C8»).Value = color
- Sheet7.Range(«C9»).Value = price
- Set discrib = Nothing
- Set color = Nothing
- Set price = Nothing
- End If
- End Sub
******************
[SIZE=6]Yours
h [/SIZE]
Your Help Is Highly Appreciated
Re: Run Time Error 9: Subscribt out of range
With a quick look does sheet 3 & 7 exist?
Re: Run Time Error 9: Subscribt out of range
chances are that «code» is not found
In formulae, depending on your locale, you might have to replace [B] ; with , or vice versa.[/B]
Re: Run Time Error 9: Subscribt out of range
check that the workbook you are searching in is the active workbook. And also ensure that the sheet name is actually «sheet3».
Subscript out of range usually means that you can’t gain focus to the object you are searching. Hence it is out of range (you can’t get hold of it)
Most people would prefer to use the code name of the sheet they are searching so that it isn’t potentially changed by the user so in this case you might want to check the code name and refer to it like Sheet3.Range(«A3:A3000»).Find etc. NB. The code name can be changed by selecting the properties of each sheet in the VBE.
Thread: [RESOLVED] [Excel] Subscript out of range
Thread Tools
Display
- Linear Mode
- Switch to Hybrid Mode
- Switch to Threaded Mode
[RESOLVED] [Excel] Subscript out of range
I am working in Excel version 6.5 and the following code opens the workbook but the attempt to copy gives «Subscript out of range» error.
The «Source» w/Book is known to have all the sheets named and the «Recipient w/book is known to have only one sheet.
MyBook is the total path plus file name plus extension (.xlsx).
How can I find out which «Subscript» is causing the error?
Re: [Excel] Subscript out of range
I can’t see it off-hand, but that line contains several
«candidates». So, perhaps in the name of trouble-shooting,
the following code might help you drill down to the issue.
.. or something along those lines to see which line
triggers the error.
Re: [Excel] Subscript out of range
Thank you oops; Have you been up all night?
This is the sort of thing I was looking for, to help me get closer to the failure. I am still not !00% sure that the W/Books are good in every respect but they behave perfectly if I do these operations manually in excel. Is there any way that one can get a «health check» on workbooks to say what type they are (.xls, .xlsx, etc) and whether their internal format matches the extension? That would allay my fears, one way or the other!
I will now give it a try.
Re: [Excel] Subscript out of range
Re up all night .. well, it sometimes seems that way.
Re health check .. I’m not quite sure what you mean
here. Perhaps you could elaborate by giving some examples
of what you are talking about, what environment you are
working in (one computer, LAN, who creates the WB’s, etc).
Re: [Excel] Subscript out of range
Re: [Excel] Subscript out of range
OK, re «computer didn’t like it» .
The concept I suggested was for debugging purposes
only, so you would insert those lines just above the
«big» line that has the several candidate sources of error.
Try this in the sub you already have:
Then do these steps .
- Put a breakpoint on the «v1 = . » line.
- Then run you macro
- The macro will stop at the breakpoint.
- Then step through the lines of code one line at a time .. press the F8 key once.
- If you get an error on the v1 line, then stop .. we’ll need to deal with that
- If you get over v1 ok, then press the F8 key one more time
- If you get an error on v2, then stop ..
- I think you get the idea.
- I’m trying to find out which of the 4 lines cause an error
Let me know which line is the first one to cause an error
and what the error is.
My bad ..
I just tried the v1 line myself as a test and it crashes,
>> error: Object doesn’t support this property or method.
I now realize that I was improperly trying to parse the
«big» line of code.
So, please disregard my above suggestions.
I must now confess that I do NOT currently have a
solution for you. Sorry to have misled you.
My only remaining hunch is that it has something to do
with the Array(«Income» . «Budget») parameter.
Hopefully someone who uses Excel more than I do
will have an answer for you.
How To Fix VBA Subscript out of range
To Fix (VBA Subscript out of range) error you need to follow the steps below:
Совместимость : Windows 10, 8.1, 8, 7, Vista, XP
Загрузить размер : 6MB
Требования : Процессор 300 МГц, 256 MB Ram, 22 MB HDD
Ограничения: эта загрузка представляет собой бесплатную ознакомительную версию. Полный ремонт, начиная с $ 19.95.
VBA Subscript out of range обычно вызвано неверно настроенными системными настройками или нерегулярными записями в реестре Windows. Эта ошибка может быть исправлена специальным программным обеспечением, которое восстанавливает реестр и настраивает системные настройки для восстановления стабильности
If you have VBA Subscript out of range then we strongly recommend that you Download (VBA Subscript out of range) Repair Tool .
This article contains information that shows you how to fix VBA Subscript out of range both (manually) and (automatically) , In addition, this article will help you troubleshoot some common error messages related to VBA Subscript out of range that you may receive.
Примечание: Эта статья была обновлено на 2020-03-31 и ранее опубликованный под WIKI_Q210794
Contents [show]
Апрельское обновление 2020:
We currently suggest utilizing this program for the issue. Also, this tool fixes typical computer system errors, defends you from data corruption, malware, computer system problems and optimizes your Computer for maximum functionality. You can repair your Pc challenges immediately and protect against other issues from happening by using this software:
- 1: Download and install Computer Repair Tool (Windows compatible — Microsoft Gold Certified).
- 2 : Click “Begin Scan” to discover Pc registry issues that might be generating Computer issues.
- 3 : Click on “Fix All” to fix all issues.
Meaning of VBA Subscript out of range?
VBA Subscript out of range is the error name that contains the details of the error, including why it occurred, which system component or application malfunctioned to cause this error along with some other information. The numerical code in the error name contains data that can be deciphered by the manufacturer of the component or application that malfunctioned. The error using this code may occur in many different locations within the system, so even though it carries some details in its name, it is still difficult for a user to pinpoint and fix the error cause without specific technical knowledge or appropriate software.
Causes of VBA Subscript out of range?
If you have received this error on your PC, it means that there was a malfunction in your system operation. Common reasons include incorrect or failed installation or uninstallation of software that may have left invalid entries in your Windows registry, consequences of a virus or malware attack, improper system shutdown due to a power failure or another factor, someone with little technical knowledge accidentally deleting a necessary system file or registry entry, as well as a number of other causes. The immediate cause of the «VBA Subscript out of range» error is a failure to correctly run one of its normal operations by a system or application component.
More info on VBA Subscript out of range
It refers to this line: selectedMfsPrices(numMfsSelected) = are selected ‘allCarMfs() holds the name of Cars. ‘SelecetedCarMfs() holds the selected Cars. Heres the rest allMfsPrices(i) Any help would be much welcomed. code to output car manufacturers names and prices, through a user form. However when I try to execute my code it says «Subscript out of range».
Thanks Private Sub cmd_ShowSelected_Click() Dim i prices of Mfs ‘Second part holds selected prices of Mfs Dim allMfsPrices() As Double, selectedMfsPrices() As Double ‘list_Car. ListCount. Hi I’m new at VBA I have been writing up a Of manufacturers. ‘numMfsSelected is used to count how many times Mfs of my code.
Second part the array containing selected Mfs ReDim Preserve selectedCarMfs(numMfsSelected) ReDim Preserve selectedMfsPrices(numMfsSelected) Sheet2.Activate list_SelectedMfs.List = selectedCarMfs End Sub ReDim allMfsPrices(numlistedItems), selectedMfsPrices(numlisedItems) i believe should be ReDim allMfsPrices(numlistedItems), selectedMfsPrices(numlisTedItems) you left the ‘t’ out of ‘numlistedItems’ Dim numlistedItems As Integer, numMfsSelected As Integer Dim allCarMfs() As String, selectedCarMfs() As String ‘First part holds As Integer ‘numListedItems holds total no. Индекс вне диапазона
I have an array declared and LBound(UserListArray)
UBound(UserListArray)
not initialized as:
Public UserListArray() As String.
odd error which is coming up with «subscript out of range (te)». my entire code below. Again, I’ve pasted
I have pasted the entire code below.
Anyway, after typing in the script, I am now getting an runtime error 9 subscript out of range, huh?
For the last few days, when I open a toolbars at the top of the screen, just under the regular IE toolbar. It URL to another, same error message. I don’t know where which I prefer. I’ve never seen that and got no results.
Also when I change from one error box, it says ‘whaimager’. I clicked view/toolbars/whaimager toolbar got rid of those toolbars, so I think they are related. Only IE, and found no help there. Oh, btw, there is no longer an going on?
I think the error message started showing up when I the toolbars came from. The odd thing is, a few days ago I suddenly had 2 extra before on an error box. Anyone have any idea what’s had a lot of options for search engines, like google, alta vista, etc. The other thing is, I do not get the error message when I use my yahoo browser.
At the top of the is gone. I googled whaimager new window in IE I get this error message. I’ve checked microsoft knowledge base and both extra toolbars disappeared. One was a yahoo toolbar, and one said «my seach» and it option in view/toolbars for a whaimager toolbar.
Did you install or remove something right about that time?Windows 7 News! Когда это началось? Run-time error ‘9’: Subscript out of range
I think it’s a oppinions? What did exe files, all were working fine. Last night I downloaded some problem with the unicode.
Thanks you download?
Some of the exe files start for x64 installed on my laptop.
Hi, dear friends. Any a while about 1-2 sec and crashes.
They generally mean that VBA has stumbled go on. I could
Best of you can do with that? Why don’t you see what upon a statement that it can’t figure out. luck!
Runtime error 9, Subscript out of Range
Q = Split(RULES(i, 6), «;»)
Rollin
that you have not included in your code? Best Regards
Is «RULES» a separate function
Am trying to import Excel data into Access (using 2007 versions but
Any help welcome!! all files saved as 2000 format) and getting ‘subscript out of range’ error. I looked around for similar problems and found it mostly occurs when running macros, which I am not.
I kept having a runtime error one sheet and paste it on another worksheet (Summary_Receipt_Fees) from B2 onwards. My codes is to copy the data from B6 onwards from that said subscript out of range.
Hi,I’m currently doing a macro in Office 2010 (Excel). сообщение Ошибка времени выполнения «9»
привет всем, я продолжаю получать это сообщение Run
Какую программу вы используете?
Может кто-нибудь помочь, пожалуйста, поблагодарить u
Ошибка времени «9». [VBA + Excel 2k3] Runtime error 9, Subscript out of Range
if ubound(q)>=1 then
If Not Best Regards
iboumiza
fixed ! Cells(Int(q(0)), Int(q(1))).Value = «» Then
.
Мы не можем импортировать 66 lakhs. Импорт строк Office 2010
Я работаю одновременно с файлом excel.
Когда я импортирую электронную таблицу Excel в БД доступа, мастер импорта дает мне диалоговое окно, в котором указано, что индекс находится вне допустимого диапазона.
how to do it at the moment.. Basically I have created sum ranges that hold to VBA and its functionality. What I am aiming to do is have it such that when i
Hi first off I’m new choose england for instance i can only choose the english counties from my range.
So please be nice ! But am kind of clueless at my data for countries and locations (as in counties).. Solved: access vba array «Subscript out of Range»
Any suggestions is in ReasCount. and with and without the () brackets. The error is a line. (especially since using access 2007 multivalue lists do not work well in vba. I really need some
When entering the «Reason» field, if an Overall Result field is «2» (which equals at 11 fields and then corresponds them to the correct error. Right now I’ve been getting an the correct error and chk is the showing the correct number. I have the following code in which an array looks or questions? Putting my cursor over the fields show that ReasArray is pulling for looking at this post.
The error error on the line ReasCount(chk) = ReasArray(i). If there are multiple errors, my result should be a small list of the errors. George
I’ve used it as a variant a Fail), then the loop kicks in to count and respond the failed items.
Hi everyone, thank you Subscript out of Range error. I’ve thought about returning an array so I can list multiple values in one feedback on this one. Run rime error «9» subscript out of range
— самый длинный, чтобы иметь 3 диапазоны (строки) данных (раз). Я думаю, что это подтолкнуло меня до предела моих знаний. Если знаменатель достаточно велик, вы даже не увидите, например, строку Auto-sort 2 в строке 4 на основе строки 3, то же значение, например,
Поэтому, если у вас есть, и я пытался найти ответ с десятков сайтов, но . COLUMN () вернет 2. В колонке B, легкость объяснения, я предлагаю строку помощника. Вставьте строку выше своего времени в пути.
Это можно сделать с помощью того, что называется «Строка помощника» (или столбца). Для разницы, но внутри Excel все номера будут разными. будет эквивалентен: = LARGE ($ B $ 3: $ I $ 3,1), который вернет самое длинное время поездки в B3: I3. Вы
В столбце C = COLUMNS () вернет 3 и т. Д. Поэтому в столбце B LARGE ($ B $ 3: $ I $ 3, COLUMN () — 1) моя последняя надежда.
I have a party comming up and the songs I chose are not able to be played right now.
All my mp3 files now show up with the VBS subscript icon next to them and I can’t play them.
HELP . What do I do?
I quite often need to use either for just one CTRL+SHIFT+=Subscript: CTRL+=
is there anyway to create a shortcut in character and having to go through the format->font menu takes awhile. Thanks
Superscript: word so that you can easily switch to sub/superscript. Superscript and subscript in Word
Check for subscript out of range
LinkBack
Thread Tools
Rate This Thread
Display
- Linear Mode
- Switch to Hybrid Mode
- Switch to Threaded Mode
Check for subscript out of range
In a function I want to fill an array with values. This function goes
through a given column on a sheet (say coumn B) and stores the values in the
array, skipping all the duplicates. Every time the function is called the
array is redimmed so it starts with an ’empty’ array and then fills it.
Now in the next column (column C) i also have some values which also have to
be put into the array, again skipping the duplicates. Depending on if column
B was empty or not, the array has already got some values in it. When
proceeding to column C how can i check if the array is already populated by
at least 1 value?
I cannot use Ubound, but I can also not check for the error (subscript is
out of range) by using IsError, or something else.
code:
dim boolArrayHasNoValues as Boolean
Re: Check for subscript out of range
John Walkenbach shows how to get a nice unique list at:
http://j-walk.com/ss/excel/tips/tip47.htm
Paul wrote:
>
> Hi all,
>
> In a function I want to fill an array with values. This function goes
> through a given column on a sheet (say coumn B) and stores the values in the
> array, skipping all the duplicates. Every time the function is called the
> array is redimmed so it starts with an ’empty’ array and then fills it.
>
> Now in the next column (column C) i also have some values which also have to
> be put into the array, again skipping the duplicates. Depending on if column
> B was empty or not, the array has already got some values in it. When
> proceeding to column C how can i check if the array is already populated by
> at least 1 value?
>
> I cannot use Ubound, but I can also not check for the error (subscript is
> out of range) by using IsError, or something else.
>
> code:
> dim boolArrayHasNoValues as Boolean
>
> boolArrayHasNoValues = IsError(UBound(NoDuplicates)) of range
>
> »if NoDuplicates is not yet redim / rather if NoDuplicates has no values
> yet then
>
> For iTemp = 1 To AllCells.Cells.Count
> ‘get first value in selection of cells, and stop this part of
> the function
> ‘this is to make sure that there are no empty values in the
> array
> If Not AllCells.Cells(iTemp) = «» Then
> ReDim NoDupes(1)
> NoDupes(1) = AllCells.Cells(iTemp)
> Exit For
> End If
> Next iTemp
> »End If
Re: Check for subscript out of range
Two choices to address your specific question. However, you may also
want to check out the Collection object as a means to quickly create a
unique list.
Choice 1: Always create the array with a ‘unused’ lbound. So, an
’empty’ array will be
Dim MyArr()
ReDim MyArr(0 to 0)
Now, one can always test UBound. If zero it means the array has never
been used.
Choice 2: Use a error trap
On Error Resume Next
x=ubound(y)
if err.number<>0 then ‘array is uninitialized
On Error Goto 0
Tushar Mehta
www.tushar-mehta.com
Excel, PowerPoint, and VBA add-ins, tutorials
Custom MS Office productivity solutions
In article , «Paul»
HEREGOESTHEAD Gmail.com> says.
> Hi all,
>
> In a function I want to fill an array with values. This function goes
> through a given column on a sheet (say coumn B) and stores the values in the
> array, skipping all the duplicates. Every time the function is called the
> array is redimmed so it starts with an ’empty’ array and then fills it.
>
> Now in the next column (column C) i also have some values which also have to
> be put into the array, again skipping the duplicates. Depending on if column
> B was empty or not, the array has already got some values in it. When
> proceeding to column C how can i check if the array is already populated by
> at least 1 value?
>
> I cannot use Ubound, but I can also not check for the error (subscript is
> out of range) by using IsError, or something else.
>
>
> code:
> dim boolArrayHasNoValues as Boolean
>
> boolArrayHasNoValues = IsError(UBound(NoDuplicates)) of range
>
> »if NoDuplicates is not yet redim / rather if NoDuplicates has no values
> yet then
>
> For iTemp = 1 To AllCells.Cells.Count
> ‘get first value in selection of cells, and stop this part of
> the function
> ‘this is to make sure that there are no empty values in the
> array
> If Not AllCells.Cells(iTemp) = «» Then
> ReDim NoDupes(1)
> NoDupes(1) = AllCells.Cells(iTemp)
> Exit For
> End If
> Next iTemp
> »End If
>
>
>
>
>
>
Re: Check for subscript out of range
Thanks Dave an Tushar for ur responses.
A example similar to the tip on John Walkenbach’s site was my starting
point. But I was looking for the fasted way to check if an array was empty
or not.
I had thought about checking if there is a cell in Column B which isn’t
emtpy but I thought there had to be a better way to check if an array is
empty (don’t know if that is the correct term for it). Putting an ’empty’
value in lbound is the fasted and easiest way. Thanks for that.
«Tushar Mehta» wrote in message
news:MPG.1cb9c08c58c051cd98af6b@msnews.microsoft.com.
> Two choices to address your specific question. However, you may also
> want to check out the Collection object as a means to quickly create a
> unique list.
>
> Choice 1: Always create the array with a ‘unused’ lbound. So, an
> ’empty’ array will be
> Dim MyArr()
> ReDim MyArr(0 to 0)
>
> Now, one can always test UBound. If zero it means the array has never
> been used.
>
> Choice 2: Use a error trap
> On Error Resume Next
> x=ubound(y)
> if err.number<>0 then ‘array is uninitialized
> On Error Goto 0
>
> —
> Regards,
>
> Tushar Mehta
> www.tushar-mehta.com
> Excel, PowerPoint, and VBA add-ins, tutorials
> Custom MS Office productivity solutions
>
> In article , «Paul»
> HEREGOESTHEAD Gmail.com> says.
>> Hi all,
>>
>> In a function I want to fill an array with values. This function goes
>> through a given column on a sheet (say coumn B) and stores the values in
>> the
>> array, skipping all the duplicates. Every time the function is called the
>> array is redimmed so it starts with an ’empty’ array and then fills it.
>>
>> Now in the next column (column C) i also have some values which also have
>> to
>> be put into the array, again skipping the duplicates. Depending on if
>> column
>> B was empty or not, the array has already got some values in it. When
>> proceeding to column C how can i check if the array is already populated
>> by
>> at least 1 value?
>>
>> I cannot use Ubound, but I can also not check for the error (subscript is
>> out of range) by using IsError, or something else.
>>
>>
>> code:
>> dim boolArrayHasNoValues as Boolean
>>
>> boolArrayHasNoValues = IsError(UBound(NoDuplicates)) > out
>> of range
>>
>> »if NoDuplicates is not yet redim / rather if NoDuplicates has no values
>> yet then
>>
>> For iTemp = 1 To AllCells.Cells.Count
>> ‘get first value in selection of cells, and stop this part of
>> the function
>> ‘this is to make sure that there are no empty values in the
>> array
>> If Not AllCells.Cells(iTemp) = «» Then
>> ReDim NoDupes(1)
>> NoDupes(1) = AllCells.Cells(iTemp)
>> Exit For
>> End If
>> Next iTemp
>> »End If
>>
>>
>>
>>
>>
>>
Re: Check for subscript out of range
If I were using an array, I think I’d just use a boolean variable and keep track
of it there. Reset it to false each time you empty the array and set it true
the first time you add something to it.
But for a collection, you can just look at the count.
Stealing from John Walkenbach’s code:
Option Explicit
Sub RemoveDuplicates()
Dim AllCells As Range, Cell As Range
Dim NoDupes As New Collection
Set AllCells = Range(«A1:A105»)
On Error Resume Next
For Each Cell In AllCells
If Trim(Cell.Value) <> «» Then
NoDupes.Add Cell.Value, CStr(Cell.Value)
End If
Next Cell
On Error GoTo 0
If NoDupes.Count = 0 Then
‘nothing added
MsgBox «No cells added»
Else
‘do what you want.
MsgBox «Added » & NoDupes.Count & » unique entries» _
& vbLf & «From a possible: » & AllCells.Cells.Count
End If
Paul wrote:
>
> Thanks Dave an Tushar for ur responses.
>
> A example similar to the tip on John Walkenbach’s site was my starting
> point. But I was looking for the fasted way to check if an array was empty
> or not.
>
> I had thought about checking if there is a cell in Column B which isn’t
> emtpy but I thought there had to be a better way to check if an array is
> empty (don’t know if that is the correct term for it). Putting an ’empty’
> value in lbound is the fasted and easiest way. Thanks for that.
>
> «Tushar Mehta» wrote in message
> news:MPG.1cb9c08c58c051cd98af6b@msnews.microsoft.com.
> > Two choices to address your specific question. However, you may also
> > want to check out the Collection object as a means to quickly create a
> > unique list.
> >
> > Choice 1: Always create the array with a ‘unused’ lbound. So, an
> > ’empty’ array will be
> > Dim MyArr()
> > ReDim MyArr(0 to 0)
> >
> > Now, one can always test UBound. If zero it means the array has never
> > been used.
> >
> > Choice 2: Use a error trap
> > On Error Resume Next
> > x=ubound(y)
> > if err.number<>0 then ‘array is uninitialized
> > On Error Goto 0
> >
> > —
> > Regards,
> >
> > Tushar Mehta
> > www.tushar-mehta.com
> > Excel, PowerPoint, and VBA add-ins, tutorials
> > Custom MS Office productivity solutions
> >
> > In article , «Paul»
> > HEREGOESTHEAD Gmail.com> says.
> >> Hi all,
> >>
> >> In a function I want to fill an array with values. This function goes
> >> through a given column on a sheet (say coumn B) and stores the values in
> >> the
> >> array, skipping all the duplicates. Every time the function is called the
> >> array is redimmed so it starts with an ’empty’ array and then fills it.
> >>
> >> Now in the next column (column C) i also have some values which also have
> >> to
> >> be put into the array, again skipping the duplicates. Depending on if
> >> column
> >> B was empty or not, the array has already got some values in it. When
> >> proceeding to column C how can i check if the array is already populated
> >> by
> >> at least 1 value?
> >>
> >> I cannot use Ubound, but I can also not check for the error (subscript is
> >> out of range) by using IsError, or something else.
> >>
> >>
> >> code:
> >> dim boolArrayHasNoValues as Boolean
> >>
> >> boolArrayHasNoValues = IsError(UBound(NoDuplicates)) >> out
> >> of range
> >>
> >> »if NoDuplicates is not yet redim / rather if NoDuplicates has no values
> >> yet then
> >>
> >> For iTemp = 1 To AllCells.Cells.Count
> >> ‘get first value in selection of cells, and stop this part of
> >> the function
> >> ‘this is to make sure that there are no empty values in the
> >> array
> >> If Not AllCells.Cells(iTemp) = «» Then
> >> ReDim NoDupes(1)
> >> NoDupes(1) = AllCells.Cells(iTemp)
> >> Exit For
> >> End If
> >> Next iTemp
> >> »End If
> >>
> >>
> >>
> >>
> >>
> >>
Re: Check for subscript out of range
Thanks Dave! I didn’t know anything about Collections (actually still don’t)
but it might be something to look into. I don’t know what the difference is
between Collections, Arrays and Dictionaries. I just now searched for Array
vs Collections, for now the array works just fine, but I’ll look into the
other two just the same.
I haven’t yet decided which solution I am going for, but using a boolean is
a good option as well.