Excel exist in table

Содержание

  1. Value exists in a range
  2. Related functions
  3. Summary
  4. Generic formula
  5. Explanation
  6. COUNTIF function
  7. Slightly abbreviated
  8. Testing for a partial match
  9. An alternative formula using MATCH
  10. Test if Value Exists in a Range in Excel & Google Sheets
  11. COUNTIF Value Exists in a Range
  12. COUNTIF Value Exists in a Range Google Sheets
  13. VBA Check If table Exists in Excel
  14. Example to to Check If a table Exists on the Worksheet
  15. Check Multiple Tables are exists on the Worksheet
  16. Instructions to Run VBA Macro Code or Procedure:
  17. Other Useful Resources:
  18. Checking if a value exists anywhere in range in Excel
  19. 4 Answers 4
  20. Check IF a Value Exists in a Range
  21. Check for a Value in a Range
  22. How this Formula Works
  23. Check for a Value in a Range Partially

Value exists in a range

Summary

To test if a value exists in a range of cells, you can use a simple formula based on the COUNTIF function and the IF function. In the example shown, the formula in F5, copied down, is:

where data is the named range B5:B16. As the formula is copied down it returns «Yes» if the value in column E exists in B5:B16 and «No» if not.

Generic formula

Explanation

In this example, the goal is to use a formula to check if a specific value exists in a range. The easiest way to do this is to use the COUNTIF function to count occurences of a value in a range, then use the count to create a final result.

COUNTIF function

The COUNTIF function counts cells that meet supplied criteria. The generic syntax looks like this:

Range is the range of cells to test, and criteria is a condition that should be tested. COUNTIF returns the number of cells in range that meet the condition defined by criteria. If no cells meet criteria, COUNTIF returns zero. In the example shown, we can use COUNTIF to count the values we are looking for like this

Once the named range data (B5:B16) and cell E5 have been evaluated, we have:

COUNTIF returns 1 because «Blue» occurs in the range B5:B16 once. Next, we use the greater than operator (>) to run a simple test to force a TRUE or FALSE result:

By itself, the formula above will return TRUE or FALSE. The last part of the problem is to return a «Yes» or «No» result. To handle this, we nest the formula above into the IF function like this:

This is the formula shown in the worksheet above. As the formula is copied down, COUNTIF returns a count of the value in column E. If the count is greater than zero, the IF function returns «Yes». If the count is zero, IF returns «No».

Slightly abbreviated

It is possible to shorten this formula slightly and get the same result like this:

Here, we have remove the «>0» test. Instead, we simply return the count to IF as the logical_test. This works because Excel will treat any non-zero number as TRUE when the number is evaluated as a Boolean.

Testing for a partial match

To test a range to see if it contains a substring (a partial match), you can add a wildcard to the formula. For example, if you have a value to look for in cell C1, and you want to check the range A1:A100 for partial matches, you can configure COUNTIF to look for the value in C1 anywhere in a cell by concatenating asterisks on both sides:

The asterisk (*) is a wildcard for one or more characters. By concatenating asterisks before and after the value in C1, the formula will count the text in C1 anywhere it appears in each cell of the range. To return «Yes» or «No», nest the formula inside the IF function as above.

An alternative formula using MATCH

As an alternative, you can use a formula that uses the MATCH function with the ISNUMBER function instead of COUNTIF:

The MATCH function returns the position of a match (as a number) if found, and #N/A if not found. By wrapping MATCH inside ISNUMBER, the final result will be TRUE when MATCH finds a match and FALSE when MATCH returns #N/A.

Источник

Test if Value Exists in a Range in Excel & Google Sheets

Download the example workbook

This tutorial demonstrates how to use the COUNTIF function to determine if a value exists in a range.

COUNTIF Value Exists in a Range

To test if a value exists in a range, we can use the COUNTIF Function:

The COUNTIF function counts the number of times a condition is met. We can use the COUNTIF function to count the number of times a value appears in a range. If COUNTIF returns greater than 0, that means that value exists.

By attaching “>0” to the end of the COUNTIF Function, we test if the function returns >0. If so, the formula returns TRUE (the value exists).

You can see above that the formula results in a TRUE statement for the name “Patrick Mitchell. On the other hand, the name “Georgia Smith” and “Patrick Svensen” does not exist in the range $B$2:$B$31.

You can wrap this formula around an IF Function to output a specific result. For example, if we want to add a “Does not exist” text for names that are not in the list, we can use the following formula:

COUNTIF Value Exists in a Range Google Sheets

We use the same formula structure in Google Sheets:

Источник

VBA Check If table Exists in Excel

VBA Check if table Exists in Excel. Let us check if a table exists on the worksheet. And also check if multiple tables are exist on the Sheet. We use ListObjects collection. In this tutorial we have explained multiple examples with explanation. We also shown example output screenshots. You can change table and sheet name as per your requirement. We also specified step by step instructions how to run VBA macro code at the end of the session.

Example to to Check If a table Exists on the Worksheet

Let us see the example to check if a table Exists on the Worksheet using VBA. The sheet name defined as ‘Table‘. And we use table name as ‘MyTable1‘. You can change these two as per your requirement.
Where ListObjects represents the collection.

Output: Here is the following output screenshot of above example macro VBA code.

Check Multiple Tables are exists on the Worksheet

Here is the another example to check if multiple tables are exists on the Worksheet using VBA.

Output: Let us see the following output screenshot of above example macro VBA code. The difference between before and after macro, see the above output screenshot.

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

Checking if a value exists anywhere in range in Excel

I want to check if the value of the cell A1 exist anywhere from sheet2!$A$2:$z$50.

IF the value exist then return the value of the 1st Row at the column where the match was found.

but this functions are limited to check if match at a single row / column.

I was hoping for something like =IF(A1,sheet2!$A$2:$Z$50,x1,FALSE) where x = the column where the match was found.

Is there something like that?

4 Answers 4

An array formula like this would work

Press Shift Ctrl Enter together

Say Sheet2 is like:

We want a formula on Sheet1 that will return the value in the header row if that column contains a value to be found. So if A1 contains Good Guy then the formula should return Victor Laszlo

Put the following UDF in a standard module:

User Defined Functions (UDFs) are very easy to install and use:

  1. ALT-F11 brings up the VBE window
  2. ALT-I ALT-M opens a fresh module
  3. paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the UDF:

  1. bring up the VBE window as above
  2. clear the code out
  3. close the VBE window

To use the UDF from Excel:

=GetHeader(A1,Sheet2!A1:Z50)

To learn more about macros in general, see:

and for specifics on UDFs, see:

Macros must be enabled for this to work!

We give the UDF the entire range including the header row (although the header row is excluded from the search)

Источник

Check IF a Value Exists in a Range

In Excel, to check if a value exists in a range or not, you can use the COUNTIF function, with the IF function. With COUNTIF you can check for the value and with IF, you can return a result value to show to the user. i.e., Yes or No, Found or Not Found.

Check for a Value in a Range

In the following example, you have a list of names where you only have first names, and now, you need to check if “Arlene” is there or not.

You can use the following steps:

  1. First, you need to enter the IF function in cell B1.
  2. After that, in the first argument (logical test), you need to enter the COUNTIF function there.
  3. Now, in the COUNTIF function, refer to the range A1:A10.
  4. Next, in the criteria argument, enter “Glen” and close the parentheses for the COUNTIF Function.
  5. Additionally, use a greater than sign and enter a zero.
  6. From here, enter a comma to go to the next argument in the IF, and enter “Yes” in the second argument.
  7. In the end, enter a comma and enter “No” in the third argument and type the closing parentheses.

The moment you hit enter it returns “Yes”, as you have the value in the range that you have searched for.

How this Formula Works

This formula has two parts.

In the first part, we have COUNTIF, which counts the occurrence of the value in the range. And in the second part, you have the IF function that takes the values from the COUNTIF function.

So, if COUNTIF returns any value greater than which means the value is there in the range IF returns Yes. And if COUNTIF returns 0, which means the value is not there in the range and it returns No.

Check for a Value in a Range Partially

There counts to be a situation where you want to check for partial value from a range. In that case, you need to use wildcard characters (asterisk *).

In the following example, we have the same list of names but here is the full name. But we still need to look for the name “Glen”.

The value you want to search for needs to be enclosed with an asterisk, which we have used in the above example. This tells Excel, to check for the value “Glen” regardless of what is there before and after the value.

Источник

In this example, the goal is to use a formula to check if a specific value exists in a range. The easiest way to do this is to use the COUNTIF function to count occurences of a value in a range, then use the count to create a final result.

COUNTIF function

The COUNTIF function counts cells that meet supplied criteria. The generic syntax looks like this:

=COUNTIF(range,criteria)

Range is the range of cells to test, and criteria is a condition that should be tested. COUNTIF returns the number of cells in range that meet the condition defined by criteria. If no cells meet criteria, COUNTIF returns zero. In the example shown, we can use COUNTIF to count the values we are looking for like this

COUNTIF(data,E5)

Once the named range data (B5:B16) and cell E5 have been evaluated, we have:

=COUNTIF(data,E5)
=COUNTIF(B5:B16,"Blue")
=1

COUNTIF returns 1 because «Blue» occurs in the range B5:B16 once. Next, we use the greater than operator (>) to run a simple test to force a TRUE or FALSE result:

=COUNTIF(data,B5)>0 // returns TRUE or FALSE

By itself, the formula above will return TRUE or FALSE. The last part of the problem is to return a «Yes» or «No» result. To handle this, we nest the formula above into the IF function like this:

=IF(COUNTIF(data,E5)>0,"Yes","No")

This is the formula shown in the worksheet above. As the formula is copied down, COUNTIF returns a count of the value in column E. If the count is greater than zero, the IF function returns «Yes». If the count is zero, IF returns «No».

Slightly abbreviated

It is possible to shorten this formula slightly and get the same result like this:

=IF(COUNTIF(data,E5),"Yes","No")

Here, we have remove the «>0» test. Instead, we simply return the count to IF as the logical_test. This works because Excel will treat any non-zero number as TRUE when the number is evaluated as a Boolean.

Testing for a partial match

To test a range to see if it contains a substring (a partial match), you can add a wildcard to the formula. For example, if you have a value to look for in cell C1, and you want to check the range A1:A100 for partial matches, you can configure COUNTIF to look for the value in C1 anywhere in a cell by concatenating asterisks on both sides:

=COUNTIF(A1:A100,"*"&C1&"*")>0

The asterisk (*) is a wildcard for one or more characters. By concatenating asterisks before and after the value in C1, the formula will count the text in C1 anywhere it appears in each cell of the range. To return «Yes» or «No», nest the formula inside the IF function as above.

An alternative formula using MATCH

As an alternative, you can use a formula that uses the MATCH function with the ISNUMBER function instead of COUNTIF:

=ISNUMBER(MATCH(value,range,0))

The MATCH function returns the position of a match (as a number) if found, and #N/A if not found. By wrapping MATCH inside ISNUMBER, the final result will be TRUE when MATCH finds a match and FALSE when MATCH returns #N/A.

Summary

This step-by-step article describes how to find data in a table (or range of cells) by using various built-in functions in Microsoft Excel. You can use different formulas to get the same result.

Create the Sample Worksheet

This article uses a sample worksheet to illustrate Excel built-in functions. Consider the example of referencing a name from column A and returning the age of that person from column C. To create this worksheet, enter the following data into a blank Excel worksheet.

You will type the value that you want to find into cell E2. You can type the formula in any blank cell in the same worksheet.

A

B

C

D

E

1

Name

Dept

Age

Find Value

2

Henry

501

28

Mary

3

Stan

201

19

4

Mary

101

22

5

Larry

301

29

Term Definitions

This article uses the following terms to describe the Excel built-in functions:

Term

Definition

Example

Table Array

The whole lookup table

A2:C5

Lookup_Value

The value to be found in the first column of Table_Array.

E2

Lookup_Array
-or-
Lookup_Vector

The range of cells that contains possible lookup values.

A2:A5

Col_Index_Num

The column number in Table_Array the matching value should be returned for.

3 (third column in Table_Array)

Result_Array
-or-
Result_Vector

A range that contains only one row or column. It must be the same size as Lookup_Array or Lookup_Vector.

C2:C5

Range_Lookup

A logical value (TRUE or FALSE). If TRUE or omitted, an approximate match is returned. If FALSE, it will look for an exact match.

FALSE

Top_cell

This is the reference from which you want to base the offset. Top_Cell must refer to a cell or range of adjacent cells. Otherwise, OFFSET returns the #VALUE! error value.

Offset_Col

This is the number of columns, to the left or right, that you want the upper-left cell of the result to refer to. For example, «5» as the Offset_Col argument specifies that the upper-left cell in the reference is five columns to the right of reference. Offset_Col can be positive (which means to the right of the starting reference) or negative (which means to the left of the starting reference).

Functions

LOOKUP()

The LOOKUP function finds a value in a single row or column and matches it with a value in the same position in a different row or column.

The following is an example of LOOKUP formula syntax:

   =LOOKUP(Lookup_Value,Lookup_Vector,Result_Vector)


The following formula finds Mary’s age in the sample worksheet:

   =LOOKUP(E2,A2:A5,C2:C5)

The formula uses the value «Mary» in cell E2 and finds «Mary» in the lookup vector (column A). The formula then matches the value in the same row in the result vector (column C). Because «Mary» is in row 4, LOOKUP returns the value from row 4 in column C (22).

NOTE: The LOOKUP function requires that the table be sorted.

For more information about the LOOKUP function, click the following article number to view the article in the Microsoft Knowledge Base:
 

How to use the LOOKUP function in Excel

VLOOKUP()

The VLOOKUP or Vertical Lookup function is used when data is listed in columns. This function searches for a value in the left-most column and matches it with data in a specified column in the same row. You can use VLOOKUP to find data in a sorted or unsorted table. The following example uses a table with unsorted data.

The following is an example of VLOOKUP formula syntax:

    =VLOOKUP(Lookup_Value,Table_Array,Col_Index_Num,Range_Lookup)

The following formula finds Mary’s age in the sample worksheet:

   =VLOOKUP(E2,A2:C5,3,FALSE)

The formula uses the value «Mary» in cell E2 and finds «Mary» in the left-most column (column A). The formula then matches the value in the same row in Column_Index. This example uses «3» as the Column_Index (column C). Because «Mary» is in row 4, VLOOKUP returns the value from row 4 in column C (22).

For more information about the VLOOKUP function, click the following article number to view the article in the Microsoft Knowledge Base:
 

How to Use VLOOKUP or HLOOKUP to find an exact match

INDEX() and MATCH()

You can use the INDEX and MATCH functions together to get the same results as using LOOKUP or VLOOKUP.

The following is an example of the syntax that combines INDEX and MATCH to produce the same results as LOOKUP and VLOOKUP in the previous examples:

    =INDEX(Table_Array,MATCH(Lookup_Value,Lookup_Array,0),Col_Index_Num)

The following formula finds Mary’s age in the sample worksheet:


    =INDEX(A2:C5,MATCH(E2,A2:A5,0),3)

The formula uses the value «Mary» in cell E2 and finds «Mary» in column A. It then matches the value in the same row in column C. Because «Mary» is in row 4, the formula returns the value from row 4 in column C (22).

NOTE: If none of the cells in Lookup_Array match Lookup_Value («Mary»), this formula will return #N/A.
For more information about the INDEX function, click the following article number to view the article in the Microsoft Knowledge Base:

How to use the INDEX function to find data in a table

OFFSET() and MATCH()

You can use the OFFSET and MATCH functions together to produce the same results as the functions in the previous example.

The following is an example of syntax that combines OFFSET and MATCH to produce the same results as LOOKUP and VLOOKUP:

   =OFFSET(top_cell,MATCH(Lookup_Value,Lookup_Array,0),Offset_Col)

This formula finds Mary’s age in the sample worksheet:

   =OFFSET(A1,MATCH(E2,A2:A5,0),2)

The formula uses the value «Mary» in cell E2 and finds «Mary» in column A. The formula then matches the value in the same row but two columns to the right (column C). Because «Mary» is in column A, the formula returns the value in row 4 in column C (22).

For more information about the OFFSET function, click the following article number to view the article in the Microsoft Knowledge Base:
 

How to use the OFFSET function

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

After checking if a cell value exists in a column, I need to get the value of the cell next to the matching cell. For instance, I check if the value in cell A1 exists in column B, and assuming it matches B5, then I want the value in cell C5.

To solve the first half of the problem, I did this…

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", "Match")

…and it worked. Then, thanks to an earlier answer on SO, I was also able to obtain the row number of the matching cell:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", "Match on Row " & MATCH(A1,B:B, 0))

So naturally, to get the value of the next cell, I tried…

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", C&MATCH(A1,B:B, 0))

…and it doesn’t work.

What am I missing? How do I append the column number to the row number returned to achieve the desired result?

 

GIG_ant

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

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

Добрый день.  
При обработке огромной базы (нужно было извлеч уникальные) пользовался методом:  
If Not .exists(TekElem) Then .Add TekElem, TekElem ,  
поэксперементировав, обнаружил что есть еще метод вида:    
.Item(TekElem) = TekElem ,  
который на 100 000 целых чисел дает прирост в скорости аж 37 %.  
Выкладываю файлик в котором проведено тестирование обоих методов, может кому понадобится!  
И на всякий случай вопрос знатокам: нет ли каких то подводных камней в методе с использованием Item? Может я его не правильно применил?

 

слэн

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

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

да, свойство item оказывается быстрее метода add..  

  хотя add можно использовать и по-другому, но все равно он чуть-чуть медленнее

 

Тоже пробовал напрямую добавлять и тот же результат :)  

  слэн, а что означает «0&»?

 

GIG_ant

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

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

насколько я знаю запись типа «0&» явно указывает компилятору что это число as Long, что бы он не терял время на определение типа числа. вот.

 

Я не про знак, а в целом, что это такое и почему именно в таком виде? :)

 

слэн

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

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

попробуйте прогнать код:  

  Sub еее()  
   Dim x  
   x = 0&  
End Sub  

  с этим знаком и без него.. — внимательно наблюдайте в locals

 

GIG_ant

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

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

Прогнал: со знаком лонг, без оного интеджер, а как это влияет на выполнение макроса (который вы дописали) ?

 

слэн, спасибо Вам! Кажется понял :)  

  1. Если «x = 0&» — значение «Empty» (Variant/Empty)  
2. Если «x = 0»  — значение 0 (Variant/Integer)  

  слэн, в Вашем варианте в словаре не задаем ключь, правильно?

 

слэн

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

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

нет, наоборот, если требуется только подсчитать уникальные, то зачем их заносить в словарь?  

  можно только ключ создавать.. но это мелочь.  

  хотя ради истины лучше было бы так:  
Private Sub Dict_add()  

  Dim TekElem As Long  

  With CreateObject(«Scripting.Dictionary»)  
   StartTime = GetTickCount ‘запоминаем начальное время  
   On Error Resume Next  

         For i = 1 To ColElemArr  
       .Add MyArr(i), TekElem  
   Next i  
   ColUnik = .Count  
   TotalTime = GetTickCount — StartTime ‘вычисляем затраченное время  
End With  

  End Sub

 

слэн

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

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

{quote}{login=GIG_ant}{date=24.03.2011 12:41}{thema=Re: }{post}Прогнал: со знаком лонг, без оного интеджер, а как это влияет на выполнение макроса (который вы дописали) ?{/post}{/quote}  
long обрабатывается быстрее..  

  32битная архитектура заточена под  работу с 32 битами, составляющими тип long

 

GIG_ant

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

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

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Добавить пару КЛЮЧ-ЗНАЧЕНИЕ в словарь можно такими способами:  
1 — метод .Add(<Key>,<Item>) — всем известен, но может вызывать ошибку если пара с таким ключом уже существует. Поэтому для выборки уникальных приходится усложнять код либо обработчиком ошибок, либо проверкой на .Exists(<Key>)  

  2 — чтением по ключу: хх=.Item(<Key>)  
Если <Key>  в словаре есть, то возвращается ассоциированное с ним ЗНАЧЕНИЕ.  
Если <Key> в словаре отсутствует, то создается новая пара с КЛЮЧОМ=<Key> и ЗНАЧЕНИЕМ=Empty, возвращается хх=Empty  

  3 — записью ЗНАЧЕНИЯ по ключу: .Item(<Key>=хх  
Если <Key> в словаре есть, то ассоциированное с ним ЗНАЧЕНИЕ заменяется на ЗНАЧЕНИЕ=хх  
Если <Key> в словаре отсутствует, то создается новая пара с КЛЮЧОМ=<Key> и ЗНАЧЕНИЕМ=хх  

  4 — Key Property — изменяет КЛЮЧ ЗАПИСИ в словаре: .Key(<Key>)=<NewKey>  
Если <Key> в словаре отсутствует, то создается новая ЗАПИСЬ с КЛЮЧОМ=<NewKey> и ЗНАЧЕНИЕМ=Empty  

  Надо бы эти методы сравнить по быстродействию, да всё руки не доходят.  

  Когда я осваивал работу со словарями, то по разным источникам накропал для себя файл с описанием объекта Dictionary и несколькими тестовыми макросами для работы с ними.  
Файл забросил на файлообменник min.us :

http://min.us/mvjlbaF  

Тот же файл — в приложении. Посмотрите. Может, кому и пригодится.

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Слэн, а если вместо:  

  TekElem = MyArr(i)  
.Item(TekElem) = TekElem  

  писать так  

  .Item(MyArr(i)) = MyArr(i)  

  ошибки не будет? Просто с моей точки знения лишнее телодвижение передвать сперва значение массива в переменную, а потом подставлять эту переменную, когда можно сразу обрабатывать значение массива. Скорости это не приносит, просто короче запись на одну строку и без использования переменной.

 

GIG_ant

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

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

Помоему использование переменной как раз и приносит скорость, так как в первом случае MyArr(i) вычисляется 1 раз, а во втором 2 раза.

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

слэн,  
а чем отличается    
GetTickCount Lib «kernel32» ()  
от    
Timer() ?  
Только тем, что Timer As Single в секундах, а GetTickCount As Long и в миллисекундах?

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

KuklP

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

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

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

{quote}{login=Alex_ST}{date=25.03.2011 09:28}{thema=}{post}слэн,  
а чем отличается …  
Только тем, что Timer As Single в секундах, а GetTickCount As Long и в миллисекундах?{/post}{/quote} Не совсем так:  
In Microsoft Windows the Timer function returns fractional portions of a second.  
Т.е. тоже в дробных частях секунд. В Макинтоше в секундах.

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

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Серёга, не понял…  
Я же так и написАл: Timer As Single, т.е., естественно, с дробной частью и, кстати, может давать значения и меньше 1 миллисекунды.  
Тогда как GetTickCount As Long даёт только ЦЕЛОЕ число миллисекунд.  

  Т.е. я так понимаю, что использование GetTickCount As Long вместо Timer As Single — это просто «ловля блох» на разнице в скорости обработки переменных  As Single и As Long ?  
Ну, тогда, т.к. они не в цикле, а определяются считанное число раз за время выполнения кода, то разница времени обработки, дейисвительно составит некоторое количество наносекунд :-)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

А ещё я только что обнаружил ошибочку в описаниях методах объекта «Scripting.Dictionary», имеющихся в и-нете и без проверки внесённую мною в свой файл-пример использования…  
Попробовал добавлять записи в словарь путём попытки переименовать несуществующий ключ ( метод .Key(<Key>)=<NewKey> ) и получил полный отлуп:    
«32811: Ошибка, определяемая приложением или объектом»  
Раньше не пробовал, принял на веру… Каюсь :-(

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#19

25.03.2011 10:27:21

Алексей, Вам и так надо сказать спасибо, за то что Вы все методы и свойства причесали в этом файле.Ну просто MSDN.  

  Спасибо за файлик, добавил к себе в мануалы, так как иногда что то и забывается :)

Спасибо

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Самое интересное, что, поискав в MSDN, я обнаружил там чёткое указание на то, что при попытке переименовать отсутствующий в словаре ключ создастся новая запись:  
«If key is not found when changing a key, a new key is created and its associated item is left empty.» (

http://msdn.microsoft.com/en-us/library/1ex01tte%28v=VS.85%29.aspx

)  
Ну, уж если MSDN теперь нельзя верить на слово, то куды же мы катимьси?

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#21

25.03.2011 10:39:25

Алексей попробуй у меня работает :)  

  Sub test()  
Set Dict = CreateObject(«Scripting.Dictionary»)  
Dict.Add 1, «Раз»  
Dict.Add 2, «Два»  
Dict.Key(1) = «Три»  
MsgBox Dict.Item(«Три»)  
MsgBox Dict.Item(2)  
End Sub

Спасибо

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Дмитрий,  
только, поработав со словарями, исходя из личного опыта я очень рекомендую использовать не сокращенную форму записи метода Add:  
oDict.Add «aaa», «bbb»  
а полную:  
oDict.Add  Key:=»aaa», Item:=»bbb»  
И это не украшательство для понимабельности.  
Просто у уже привычных многим коллекций по умолчанию сначала указывается Item, а потом уже Key : oColl.Add (Item, [Key] as String, [Before | After] as Long | String)
И поэтому получается такая путаница, что без залезания в справку (которая по словарям отсутствует) трудно при беглом разборе кода понять, что является ключом, а что значением в записях  
oDict.Add «aaa», «bbb»  
oColl.Add «aaa», «bbb»

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#23

25.03.2011 10:55:22

Спасибо, за совет, но останусь при своем!   :)    
так все же работает изменение ключа?

Спасибо

 

слэн

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

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

в первоначальном варианте myarr был типа вариант.. поэтому переприсваивание  
tekelem=myarr  давало прирост скорости, за счет того, что tekelem был типа long  

  потом я переопределил myarr  в long и переприсваивание потеряло смысл..  

    но он может опять появиться, если myarr придется брать с листа, а не получать вычислением..  

  «серьезным» недостатком timer является его цикличность величиной в сутки.. — т.е. интервал более суток им не измерить..

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Дмитрий,  
вы просто моментально наступили как раз на те грабли, о которых я предупреждал:  
Dict.Add 1, «Раз» — это аналог .Add key:=1, Item:=»Раз»  
Dict.Add 2, «Два» — это аналог .Add key:=2, Item:=»Два»  
поэтому действием:  
Dict.Key(1) = «Три»  
вы просто переназначаете СУЩЕСТВУЮЩИЙ ключ, а не добавляете новую запись.  
попробуйте вместо    
Dict.Key(1) = «Три»  
записать  
Dict.Key(33) = «Тридцать три»  
и получите «отлуп».

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#26

25.03.2011 11:15:23

Алексей, я уже понял, что «недочитал» про несуществующий ключ :)  
Спасибо

Спасибо

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#27

25.03.2011 11:19:50

кому интересно хорошее описание,про словари и не только, приведено тут:  

http://www.script-coding.com/

Спасибо

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Дмитрий,  
в моём самопальном файле-справочнике на каждой странице в первой строке — ссылки.  
В том числе и эта — ОЧЕНЬ КРУПНО — в ячейке А1 листа Dictionary(2)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

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

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

На лицо ужасный, добрый внутри

Народ!  
Кто-нибудь ещё тестаните, пожалуйста, код:  
Sub testAddToDict()  ‘ разные методы добавления записей в словарь  
  Dim xx  
  With CreateObject(«Scripting.Dictionary»)  
     .Add Key:=1, Item:=»Раз»  ‘ обычный метод .Add  
     .Item(2) = «Два»   ‘ запись в словарь ЗНАЧЕНИЯ по отсутствующему ключу  
     xx = .Item(3)   ‘ чтение из словаря ЗНАЧЕНИЯ по отсутствующему ключу (вернёт xx = Empty)  
     ‘.Key(4) = 4   ‘ переназначение отсутствующего ключа — НЕ РАБОТАЕТ !!!  
Debug.Print «Key» & vbTab & «Item»  
     For xx = 1 To .Count  
Debug.Print xx & vbTab & vbTab & .Item(xx)  
     Next xx  
  End With  
End Sub  
Так должно всё пройти.  
А вот если снять комментарий со строки ‘.Key(4) = 4 , то у меня вылетает на ней с ошибкой: «32811: Ошибка, определяемая приложением или объектом».  
А то я уж, действительно, начал сомневаться, кто врёт: мой комп/офис или всё-таки MSDN —

http://msdn.microsoft.com/en-us/library/1ex01tte%28v=VS.85%29.aspx

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Hugo

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

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

#30

25.03.2011 13:03:13

Так и есть — у меня тоже ошибка. И сейчас, и на примере R Dmitry — только в варианте «33» :)  
XL2000 Eng

Понравилась статья? Поделить с друзьями:
  • Excel exe что это такое
  • Excel exe точка входа не найдена
  • Excel exe скачать бесплатно
  • Excel edate по русски
  • Excel ean13 контрольная сумма