Vlookup vba error 2042

Per our support engineer:

Per our support engineer:

First of all, I think our buddy asked a very good question about how to handle the exception thrown by VLOOKUP function. J

Please ask our buddy refer to following KB article:

How to Use VLOOKUP or HLOOKUP to find an exact match

http://support.microsoft.com/default.aspx?scid=kb;en-us;181213

We set the last parameter of VLOOKUP to ‘FALSE’ to find the exact matched data. We can capture the exception by calling ‘ISERROR()’ function. If ‘ISERROR()’ equals to  TRUE, it means we can not find the exact matched item in the source table. Please refer to following VB code:

===========================

Dim exRange As Range

 Set exRange = Sheets(«Product»).UsedRange

 ActiveWorkbook.Names.Add Name:=»ProductRange», RefersToR1C1:=»=Sheet1!R1C1:R15C2″

 Dim currentSheet As Worksheet

 Set currentSheet = Sheets(«Receipt»)

 Dim i As Integer

 Dim strCmd As String, strCmd1 As String

 ‘No VLookup error handling

 For i = 2 To 4

    strCmd = «VLOOKUP(» & «R» & CStr(i) & «C2,Product!R1C1:R15C2,2)»

    MsgBox «Formula in Cell R» & CStr(i) & «C2: » & strCmd

    currentSheet.Range(«C» & i).FormulaR1C1 = «=» & strCmd

 Next

 ‘With VLookup error handling

  For i = 6 To 8

    strCmd = «VLOOKUP(» & «R» & CStr(i) & «C2,Product!R1C1:R15C2,2)»

    strCmd1 = «VLOOKUP(» & «R» & CStr(i) & «C2,Product!R1C1:R15C2,2, False)»

    strCmd = «IF(ISERROR(» & strCmd1 & «),»»CUSTOM ERROR»»» & «,» & strCmd & «)» ‘Handle the exception and replace the value in that cell with custom message

    MsgBox «Formula in Cell R» & CStr(i) & «C2: » & strCmd

    currentSheet.Range(«C» & i).FormulaR1C1 = «=» & strCmd

 Next

============================

Source Sheet (Product)

============================

[*this is a two column table showing product and price]

Product
 Price

 CPU A
 $100

 CPU B
 $80

 CPU C
 $120

 CPU D
 $70

 CPU E
 $150

 DDR RAM 256M
 $80

 DDR RAM 1G
 $200

 DDR RAM 512M
 $100

 Mainboard A
 $150

 Mainboard B
 $200

 Mainboard C
 $40

 Mainboard D
 $60

 Mainboard E
 $80

 Mainboard F
 $110

Target Sheet (Receipt)

===========================

[*this is a three column table showing description, product and price]

 Description
 Product
 Price

 CPU
 CPU A
 100

 RAM
 DDR RAM 256M
 200

 Mainboard
 Mainboard C
 40

   CPU
 CPU F
 CUSTOM ERROR

 RAM
 DDR RAM 512M
 100

 Mainboard
 Mainboard A
 150

Note: ‘CPU F’ is not in the source table.

-brenda (ISV Buddy Team)

Содержание

  1. Thread: Solved: vlookup error 2042
  2. Solved: vlookup error 2042
  3. Analysis functions – Excel/VBA Error values explained
  4. VBA – Ошибка 2042
  5. Почему я получаю ошибку 2042 в VBA Match?
  6. Почему я получаю ошибку 2042 в матче VBA?

Thread: Solved: vlookup error 2042

Thread Tools
Display

Solved: vlookup error 2042

i use a vlookup to find a match on a different sheet with this code:

[VBA]result = Application.VLookup(str, Sheets(3).Range(«A1:B» & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
MsgBox result
[/VBA]
and that works just fine while it finds something, but in 99,99% of the times it will not find anything.
that makes the result become «error 2042» and causing it to crash.

how can i avoid the msgbox-code when result is 2042?

[VBA]if result = «error 2042″[/VBA]
[VBA]on error goto 1:
msgbox result
1:[/VBA]
[VBA]if is not err.number = 2042[/VBA]

its probably simple, what did i do wrong?

[VBA]
On Error Resume Next
Result = Application.VLookup(MyStr, Sheets(3).Range(«A1:B» & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
If Result = «Error 2042» Then Result = «Nothing Found»
MsgBox Result
On Error GoTo 0
[/VBA]

MVP (Excel 2008-2010)

Post a workbook with sample data and layout if you want a quicker solution.

To help indent your macros try Smart Indent

Please remember to mark threads ‘Solved’

There are times when it is acceptable to use On error resume next. this seems to fit that need.

You have to be careful using it though as in the wrong usage it will ignore errors that can cause incorrect results.

oh sorry i forgott to say i dont like on error resume next since this might make the code skip by a serious thing.

[VBA]if result= «Error 2042″[/VBA]
gives me an errorcode 13 incompatible types.
i think this is because the Error 2042 is not a string, its something else.
it looks like a string when i hower the mousepointer above it, but its not.

There are times when it is acceptable to use On error resume next. this seems to fit that need.

You have to be careful using it though as in the wrong usage it will ignore errors that can cause incorrect results.

yeah.. i was typing my other reply while you wrote this.

the code i have is much more complex than this part i showed here, so a resume next is very risky in my opinion.

is there a way to say:

use on error resume next from here.
.

Post 2 restores normal error operation

MVP (Excel 2008-2010)

Post a workbook with sample data and layout if you want a quicker solution.

To help indent your macros try Smart Indent

Please remember to mark threads ‘Solved’

sweet! thanks that could work

BTW, avoid using Str as a variable. It is a VBA function. I used MyStr in my example.

MVP (Excel 2008-2010)

Post a workbook with sample data and layout if you want a quicker solution.

To help indent your macros try Smart Indent

Please remember to mark threads ‘Solved’

I was wondering if you had read past Malcolms suggestion.

lucas, yes i did read his post but since it «wont work».

if result = «Error 2042»
that crashes since its incompatible types.

and even if it would work it would change result to «Nothing found»
then do msgbox result.
that mean i would get a msgbox «all the time» with nothing found.
not really what i was hoping on.

but i had no clue about on error goto 0 means restore «default procedure».

mdmacillop: thanks i had no idea that was a function. i will change that!
i just made this code as a «test» since i wanted to make the code run faster.
i used to have a loop doing the same thing, but as the list gets bigger the code will run slower so i figured i would take care of the issue before it becomes a problem.

Источник

Analysis functions – Excel/VBA Error values explained

The Analysis Add-In functions can return several error values. For a robust Excel or VBA solution, you”ll need to know what each of these errors are, when they might occur, and how to handle them. Every solution is different, so I won’t try to explain how you should handle these error values in your solution, but instead, I’ll just list and explain the error values that you’ll probably encounter.

This article is about VBA/Excel errors only, and not the Add-In error codes that can be retrieved using SAPGetProperty and “LastError”.

I’m only detailing the errors that I’ve seen produced by the add-in (as at 1.4 SP3.1 and in Excel 2007), so if you know of any more, please add details in the comments…

Excel has a number of built in errors, as follows:

Number Cell Display Occurrence

2000 #NULL! Two range areas do not intersect.

2007 #DIV/0! A number is divided by zero.

2015 #VALUE! Incorrect type of argument or operand is used.

2023 #REF! A cell reference is invalid.

2029 #NAME? Excel doesn’t recognize text in the formula

2036 #NUM! Invalid numeric values in a formula/function.

2042 #N/A A value isn’t available to a function/formula.

Of the errors above, the Analysis add-in returns the errors below, but the occurrence rules sometimes differ slightly….

2015 – #VALUE! – This error is returned in at least 2 situations:

1. When calling a function and providing invalid arguments to the function. For example, if you call a function that expects a Data Source Alias, and you provide an Alias that doesn’t exist in the workbook, the function will return Error 2015. Note however, that the Add-In only treats certain invalid arguments as errors. For example, calling SAPGetMember with a non-existent Dimension/Member pair as the second argument, will not return an error, but instead, just a zero-length string.

2. When calling a function that you might expect to return an array, but there aren’t any values in the array. For example, calling SAPGetCellInfo (to discover a cell’s SELECTION) on a cell that is a total across all dimensions, will not return any dimensions in the array, and instead return Error 2015. It’s not really an error that indicates that the cell doesn’t have a selection, or that an error occurred with your syntax or arguments, but it is an indicator that the cell’s SELECTION dimensions actually include all row and column dimensions. Note the difference between this error and Error 2042 below. ie. There is a subtle difference between returning “no data to return” as Error 2015, and returning “non-existant data” as Error 2042.

2023 – #REF! – This error indicates that the datasource hasn’t been successfully refreshed, or has encountered an Exception. In other words, the datasource is not connected, and the function can’t return a value. The user should have been presented with an Exception dialog, with an option to Restart the session, so if you encounter this error in your code, you’ll need to handle a Restart.

2029 – #NAME! – This error isn’t actually returned by the Add-In, but instead by Excel. It indicates that the add-in is either not loaded, or that the function you’re calling isn’t registered (you might encounter this if you’re trying to call a function that is only present in a newer version of the add-in than you’re currently using, or if a function in the current version is removed in a future version of the Add-In)

2042 – #N/A – This is the error value that you’ll probably encounter most frequently with the Analysis add-in. The add-in returns this when you’ve requested data that doesn’t exist. For example, requesting DIMENSION details with SAPGetCellInfo, on a data cell, would not return any data because data cells do not have DIMENSION details.

Found any other Error values while using the add-in? Add them in the comments…

Источник

VBA – Ошибка 2042

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

Я пытаюсь применить некоторую форму эвристики в своем первоначальном решении, чтобы попытаться улучшить случайное начало, но все равно сталкиваться с ошибкой.

Основы моего первоначального алгоритма решения; выберите следующий самый большой несортированный элемент и поместите его в группу с наименьшим весом. Примечание. Я предварительно упорядочил свои элементы в порядке размера.

Я начал со следующего кода;

Где s() представляет собой пустой массив от 1 до n, который я буду заполнять позже, n – количество весов, k – количество групп, а w() – отсортированный массив весов, в моем пробном случае, n = 8, k = 3, w = (5,4,3,3,2,2,1,1).

Моя проблема возникает, когда я = 6, и я рассматриваю вес 2. Масса имеет значения (6,6,5), поэтому минимальное значение по массе j равно 5. Однако в следующей строке установка значения для l возникает ошибка. Когда я меняю l на вариант, он устанавливает его значение как Ошибка 2042, когда оно должно быть 3. Это вызывает код ошибки “Ошибка времени выполнения” 13: несоответствие типа “Из-за ошибки 2042, которая не может использоваться как индекс.

Я нашел ответ. Если я использую

Оно работает. Я не уверен, что была предыдущей ошибкой, но этот новый метод учитывает только первый раз, когда он встречает значение соответствия и возвращает этот индекс.

Источник

Почему я получаю ошибку 2042 в VBA Match?

У меня есть столбец А:

Теперь, если я введу:

в ячейку на листе я получаю

Как результат. (Это желательно)

Но когда я ввожу эту строку:

CurrentRow получает значение «Ошибка 2042».

Моим первым побуждением было убедиться, что значение 7 действительно находится в допустимом диапазоне, и так оно и было.

Следующим моим вопросом было, может быть, для функции Match требуется строка, поэтому я попытался

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

Попробуйте преобразовать значение CurrentShipment из a Integer в a Long вместо a String :

Если вы ищете функцию соответствия в обозревателе объектов, она возвращает двойное значение, поэтому я объявил переменную CurrentRow как двойную, и пока она принимает 3 варианта параметра. Попробуйте приведенный ниже код, если он работает для вас.

Для меня это работало нормально без приведения типов. Я использовал оба:

Application.WorksheetFunction.Match(CurrentShipment, Range(«A1:A5»), 0)

Application.Match(CurrentShipment, Range(«A1:A5»), 0)

Размер CurrentShipment как Integer, Double, Long или Variant, все работало нормально.

Интересно, что я ввел ваши данные в пустой лист Excel, а затем запустил исходный фрагмент кода. Он вернул 3, как и ожидалось, без необходимости преобразовывать CurrentShipment как String или Long.

Не DIM’ing CurrentRow делает его Variant по умолчанию, но даже установка обоих из них как Integer или CurrentRow как Byte не вызывает ошибку, поэтому использование Double в качестве возвращаемого типа является избыточным.

У меня было точно такое же сообщение об ошибке при попытке использовать функцию Match в книге с несколькими листами. Использование типа варианта для переменной, которая получает результат, хорошо, чтобы избежать ошибок выполнения, если субъект, который мы пытаемся сопоставить, не существует. Но моя ошибка была в расположении используемого диапазона. Крайне важно указать рабочий лист, в котором есть диапазон для поиска. В первый раз я использовал Range(. ) без ссылки на рабочий лист, и функция работала правильно только в том случае, если этот рабочий лист был активирован.

Источник

Почему я получаю ошибку 2042 в матче VBA?

У меня есть столбец A:

Теперь, если я введу:

в ячейку на листе я получаю

В результате. (Это необходимо)

Но когда я вхожу в эту строку:

CurrentRow получает значение «Ошибка 2042»

Мой первый инстинкт состоял в том, чтобы убедиться, что значение 7 действительно находится в диапазоне, и это было.

Моя следующая, возможно, функция Match потребовала строку, поэтому я попробовал

В качестве дополнительной заметки для этого и для тех, кто получит эту ошибку в будущем, с любой функцией, возвращающей возможную ошибку, тип варианта работает достаточно хорошо:

Если вы ищете функцию соответствия в обозревателе объектов, она возвращает double, поэтому я объявила переменную CurrentRow как double и пока она принимает 3 варианта параметра. Попробуйте выполнить код ниже, если он работает для вас.

Для меня это отлично работало, не набрасывая ничего. Я использовал оба:

Application.WorksheetFunction.Match(CurrentShipment, Range(«A1:A5»), 0)

Application.Match(CurrentShipment, Range(«A1:A5»), 0)

Измеренный CurrentShipment как Integer, Double, Long или Variant, все отлично работает.

Интересно, что я ввел ваши данные в пустой лист Excel, а затем выполнил ваш оригинальный фрагмент кода. Он вернул 3, как и ожидалось, без необходимости использовать CurrentShipment как String или Long.

Не DIM’ing CurrentRow по умолчанию имеет значение Variant, но даже если установить оба из них как Integer или CurrentRow в качестве байта, это не вызывает ошибку, поэтому использование Double в качестве возвращаемого типа является избыточным.

Источник

  • Home
  • Forum
  • VBA Code & Other Help
  • Excel Help
  • [SOLVED] Solved: vlookup error 2042

  1. 02-18-2009, 11:27 AM


    #1

    Solved: vlookup error 2042

    i use a vlookup to find a match on a different sheet with this code:

    [VBA]result = Application.VLookup(str, Sheets(3).Range(«A1:B» & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
    MsgBox result
    [/VBA]
    and that works just fine while it finds something, but in 99,99% of the times it will not find anything.
    that makes the result become «error 2042» and causing it to crash.

    how can i avoid the msgbox-code when result is 2042?

    i have tried

    [VBA]if result = «error 2042″[/VBA]
    [VBA]on error goto 1:
    msgbox result
    1:[/VBA]
    [VBA]if is not err.number = 2042[/VBA]

    its probably simple, what did i do wrong?


  2. 02-18-2009, 11:44 AM


    #2

    [VBA]
    On Error Resume Next
    Result = Application.VLookup(MyStr, Sheets(3).Range(«A1:B» & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
    If Result = «Error 2042» Then Result = «Nothing Found»
    MsgBox Result
    On Error GoTo 0
    [/VBA]

    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.

    To help indent your macros try Smart Indent

    Please remember to mark threads ‘Solved’


  3. 02-18-2009, 11:45 AM


    #3

    Try[VBA]On Error Resume Next[/VBA]


  4. 02-18-2009, 11:50 AM


    #4

    There are times when it is acceptable to use On error resume next…..this seems to fit that need.

    You have to be careful using it though as in the wrong usage it will ignore errors that can cause incorrect results….

    Steve
    «Nearly all men can stand adversity, but if you want to test a man’s character, give him power.»
    -Abraham Lincoln


  5. 02-18-2009, 11:55 AM


    #5

    oh sorry i forgott to say i dont like on error resume next since this might make the code skip by a serious thing.

    [VBA]if result= «Error 2042″[/VBA]
    gives me an errorcode 13 incompatible types.
    i think this is because the Error 2042 is not a string, its something else.
    it looks like a string when i hower the mousepointer above it, but its not.


  6. 02-18-2009, 11:57 AM


    #6

    Quote Originally Posted by lucas

    There are times when it is acceptable to use On error resume next…..this seems to fit that need.

    You have to be careful using it though as in the wrong usage it will ignore errors that can cause incorrect results….

    yeah.. i was typing my other reply while you wrote this.

    the code i have is much more complex than this part i showed here, so a resume next is very risky in my opinion.

    edit:

    is there a way to say:

    use on error resume next from here…
    ….

    ….

    …..

    to here.

    ?


  7. 02-18-2009, 12:04 PM


    #7

    Post 2 restores normal error operation

    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.

    To help indent your macros try Smart Indent

    Please remember to mark threads ‘Solved’


  8. 02-18-2009, 12:05 PM


    #8

    you mean on error goto 0?

    sweet! thanks that could work


  9. 02-18-2009, 12:07 PM


    #9

    BTW, avoid using Str as a variable. It is a VBA function. I used MyStr in my example.

    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.

    To help indent your macros try Smart Indent

    Please remember to mark threads ‘Solved’


  10. 02-18-2009, 12:11 PM


    #10

    I was wondering if you had read past Malcolms suggestion……

    Steve
    «Nearly all men can stand adversity, but if you want to test a man’s character, give him power.»
    -Abraham Lincoln


  11. 02-18-2009, 12:20 PM


    #11

    lucas, yes i did read his post but since it «wont work».

    if result = «Error 2042»
    that crashes since its incompatible types.

    and even if it would work it would change result to «Nothing found»
    then do msgbox result.
    that mean i would get a msgbox «all the time» with nothing found.
    not really what i was hoping on.

    but i had no clue about on error goto 0 means restore «default procedure».

    mdmacillop: thanks i had no idea that was a function. i will change that!
    i just made this code as a «test» since i wanted to make the code run faster.
    i used to have a loop doing the same thing, but as the list gets bigger the code will run slower so i figured i would take care of the issue before it becomes a problem.

    thanks alot guys!!


  12. 09-19-2013, 06:37 AM


    #12

    Quote Originally Posted by Ago
    View Post

    i use a vlookup to find a match on a different sheet with this code:

    [VBA]result = Application.VLookup(str, Sheets(3).Range(«A1:B» & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
    MsgBox result
    [/VBA]
    and that works just fine while it finds something, but in 99,99% of the times it will not find anything.
    that makes the result become «error 2042» and causing it to crash.

    how can i avoid the msgbox-code when result is 2042?

    i have tried

    [VBA]if result = «error 2042″[/VBA]
    [VBA]on error goto 1:
    msgbox result
    1:[/VBA]
    [VBA]if is not err.number = 2042[/VBA]

    its probably simple, what did i do wrong?

    Albeit an old thread, I recently had to do some vba excel work and came across this same issue. I’m not a fan of using «on error resume next» so i followed this solution:

    dim vresult as variant
    vresult = Application.VLookup(str, Sheets(3).Range("A1:B" & Cells(Rows.Count, 1).End(xlUp).Row), 2, False)
    If IsError(vresult ) Then
    ' do what you need to do
    else
    ' do something else
    End If

    Hope this helps someone in future…


  13. 09-21-2013, 07:57 PM


    #13

    Kobudotoit,

    Welcome to VBA Express, and thanks for the alternate solution. I’m sure someone will find it handy

    I expect the student to do their homework and find all the errrors I leeve in.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

 

Во второй строке #Н/Д, этот код запинается и выдает ошибку, как сделать так что бы действия в положительном блоке IF производились, или формулируя по другому, как сделать так что бы код выделял #Н/Д цветом?  

  Sub Oshibka()  
For i = 2 To 27  
iValue = Cells(i, 2).Value ‘Что такое Error 2042  
If Cells(i, 2).Value = «#Н/Д» Then  
Cells(i, 2).Interior.ColorIndex = 35  
End If  
Next i  
End Sub

 

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

 

Может я чего недостаточно пояснил? Скажите, так я поясню.  
Очень нужна помощь.

 

A_Zeshko

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

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

Sub Oshibka()  
For i = 1 To 27  
iValue = Cells(i, 2).Text  
If iValue = «#Н/Д» Then  
Cells(i, 2).Interior.ColorIndex = 35  
End If  
Next i  
End Sub

At odd moments: VBA, VB6, VB.NET, Java, Java for Android, Java Script, Action Script, Windows Scriping Host

 

Спасибо за ответ!  

  А можно как то определить, например, что если Cells(i, 2) — ошибка, то выполняем условие?

 

New

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

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

Sub Макрос1()  
Dim Rng As Range  
   On Error Resume Next  
   Set Rng = Columns(«B:B»).SpecialCells(xlCellTypeFormulas, 16)  
   If Not Rng Is Nothing Then Rng.Interior.ColorIndex = 35  
End Sub

 

New

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

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

Можно, конечно, и так, но это дольше, чем мой первый вариант (если ячеек много)  

  Sub Макрос1()  
Dim i&  
   For i = 1 To 27  
       If IsError(Cells(i, 2)) Then Cells(i, 2).Interior.ColorIndex = 35  
   Next i  
End Sub

 

Lant

Гость

#8

29.11.2008 18:03:27

О! Павел то что нужно, спасибо!

  • #2

varName = Application.VLookup(cell.Value, Sheet1.Range(«$A$6:$G$371»), 7, False)

should be

varName = Application.Evaluate (VLookup(cell, Sheet1.Range(«A6:g371»), 7, False))

Also, you don’t need those $ signs in VBA Code.

Your problem lied in your not telling the application to evaluate the formula…

But this will be more efficient:
<font face=Courier New><SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>Sub</SPAN>
<SPAN style=»color:#00007F»>Private</SPAN> <SPAN style=»color:#00007F»>Sub</SPAN> cmdCalendar_Click()

<SPAN style=»color:#00007F»>Dim</SPAN> myRange <SPAN style=»color:#00007F»>As</SPAN> Range
<SPAN style=»color:#00007F»>Dim</SPAN> varName <SPAN style=»color:#00007F»>As</SPAN> Range
<SPAN style=»color:#00007F»>Dim</SPAN> intColor <SPAN style=»color:#00007F»>As</SPAN> <SPAN style=»color:#00007F»>Integer</SPAN>
<SPAN style=»color:#00007F»>Dim</SPAN> c <SPAN style=»color:#00007F»>As</SPAN> Range

<SPAN style=»color:#00007F»>Set</SPAN> myRange = Range(«C3:AJ24»)

<SPAN style=»color:#00007F»>For</SPAN> <SPAN style=»color:#00007F»>Each</SPAN> c <SPAN style=»color:#00007F»>In</SPAN> myRange

<SPAN style=»color:#00007F»>If</SPAN> IsDate(c) <SPAN style=»color:#00007F»>Then</SPAN>
<SPAN style=»color:#00007F»>Set</SPAN> varName = myRange.Find(c)
<SPAN style=»color:#00007F»>If</SPAN> <SPAN style=»color:#00007F»>Not</SPAN> varName <SPAN style=»color:#00007F»>Is</SPAN> <SPAN style=»color:#00007F»>Nothing</SPAN> <SPAN style=»color:#00007F»>Then</SPAN>
<SPAN style=»color:#00007F»>Select</SPAN> <SPAN style=»color:#00007F»>Case</SPAN> c.Offset(, 6)
<SPAN style=»color:#00007F»>Case</SPAN> «Working»
intColor = Range(«F26»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «RDO»
intColor = Range(«F27»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «Chart Day»
intColor = Range(«F28»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «Vacation Day»
intColor = Range(«F29»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «Sick Day»
intColor = Range(«F30»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «Military Day»
intColor = Range(«F31»).Interior.ColorIndex
<SPAN style=»color:#00007F»>Case</SPAN> «Lost Time»
intColor = Range(«F32»).Interior.ColorIndex
<SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>Select</SPAN>
c.Interior.ColorIndex = intColor
<SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>If</SPAN>
<SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>If</SPAN>

<SPAN style=»color:#00007F»>Next</SPAN> c

<SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>Sub</SPAN>
</FONT>

It would also be easier to just identify the color index in the code (1 is Black, 3 is red, 6 is yellow…etc) rather than pulling the color from another cell….but not a too noticeable difference in speed i imagine.

  • #3

Hello,

varName = Application.VLookup(cell.Value, Sheet1.Range(«$A$6:$G$371»), 7, False)

should be

varName = Application.Evaluate (VLookup(cell, Sheet1.Range(«A6:g371»), 7, False))

No, with all due respect, Evaluate wants a String.

Evaluate Method

Converts a Microsoft Excel name to an object or a value.

expression.Evaluate(Name)
expression Optional for Application, required for Chart, DialogSheet, and Worksheet. An expression that returns an object in the Applies To list.

Name Required String. The name of the object, using the naming convention of Microsoft Excel.

You can and want to use VLookup as is, with the Application qualification.

I would add .Value to the end of your Range, Excel’s Lookup Functions want arrays, not Range Objects…

It means you’re not returning a match. When you say formatting, try to format them the same just to test. If one’s text and the other is a serial date, you should expect your Lookup to fail every time. ;)

  • #4

Nate you are the best. I added the .Value to the Range object and it worked. Thank you very much.

  • #5

Glad to help, you are welcome. :)

Incidentally, welcome to the board. :cool:

  1. 06-24-2021, 10:48 AM


    #1

    box-o-rocks is offline


    Registered User


    VLookup Error 2042 & Data not correct

    I’m having trouble with VLookup. I’ve used this before, but for some reason on this project, the data seems to be mismatched or it is not reading anything.
    I have attached the file, but the error is occurring during the following example;
    Select Copper, Single Conductor, Steel Conduit, AWG #12. Note the error occurs between Range B6:B15.
    Range B16:B27 outputs as expected
    I have changed Dim C and Wire to be String, Variant, Integer, Long… not sure what is going on with the Vlookup. Would someone be able to help? Thank you!!

    B C
    6 Copper
    7 #14 389
    8 #12 617
    9 #10 981
    10 #8 1557
    11 #6 2425
    12 #4 3806
    13 #3 4774
    14 #2 5907
    15 #1 7293
    16 1/0 8925
    17 2/0 10755
    18 3/0 12844


  2. 06-24-2021, 11:53 AM


    #2

    Re: VLookup Error 2042 & Data not correct

    First, your description of how to produce the error has some holes in it. Remember that you have been working on this and know it inside and out but we have never seen it before and have no idea what it’s supposed to do or how to use it.

    I figured out that you are talking about entering data in a UserForm. To show the UserForm I found a button on Sheet4 called «Three Phase Short Circuit». Then the form comes up and I can see where I can select Copper, Single Conductor, Steel Conduit under the header «Conductor Values» (you should be using option buttons for those instead of checkboxes). I also found the AWG value. But then…what happens? There is no button on the form to do anything next. So I just close the form. Then I look at the data in your post. It matches the data on sheet «C» Value so I guess that is the right place.

    But none of this caused an error. I finally got the error when I selected #12 and then also clicked on it after I selected it. Aside from your VLOOKUP problem I think you need to rethink your user interface.

    So the VLOOKUP problem is that your data is not sorted but you have omitted the fourth argument to VLOOKUP. You can easily diagnose this by putting the same VLOOKUP formula directly in your worksheet, and you will see it returns #N/A. To fix this, add False as the last argument, which finds only an exact match and does not require sorted data.

    Jeff
    | | |?| |?| |?| |?| | |:| | |?| |?|
    Read the rules
    Use code tags to [code]enclose your code![/code]


  3. 06-24-2021, 03:38 PM


    #3

    box-o-rocks is offline


    Registered User


    Re: VLookup Error 2042 & Data not correct

    Thank you. I’m still trying to get used to VBA.

    When you said to rethink my user interface, did you mean the UserForm layout or do you think I should utilize a different platform?


  4. 06-24-2021, 05:34 PM


    #4

    Re: VLookup Error 2042 & Data not correct

    Your overall idea is good, the platform is fine. I meant the UserForm layout.

    • When the user hits a checkbox, and «oops, I need to change that» happens, the other checkbox has been disabled, and they can’t. That’s why I suggested using option buttons, which automatically allow you to pick either one or the other.
    • The user enters a bunch of data and there is no feedback to the user that anything happened, or what the user should do next.
    • Your method depends on the user clicking on AWG, which also means they have to enter the data in the exact right order, otherwise the processing could occur prematurely.
    • There are no buttons. How are you supposed to close the form? The only thing the user can do is X out. The textbook method is to add a Submit button, and don’t change anything in the worksheets until the user hits that button, and then apply the changes and close the form. (


elf27


  • #1

I’m trying to do a simple vlookup in Excel but getting an error when I step
through the process…
Anyone know what’s wrong?

Public Sub SyncSheet2()
Const ArtCol As String = «A» ‘<=== change to suit
Dim i As Long
Dim T As Long
Dim FirstRow As Long
Dim LastRow As Long
Dim NextRow As Long
Dim CellVal As Variant
Dim DataCol As Variant
Dim ArtNum As String
Dim LookUpRng As Range
Dim sh As Worksheet

Set sh = Sheet2

With sh

i = 1
Do Until FirstRow <> 0
If IsNumeric(.Cells(i, «A»)) Then
If .Cells(i, «A»).Value > 0 Then
FirstRow = i
End If
Else: FirstRow = 0
End If
i = i + 1
Loop
i = 1
Do Until LastRow <> 0
If .Cells(i + 2, «A»).Value = «» Then
LastRow = i + 1
Else: LastRow = 0
i = i + 1
End If
Loop
End With

With sh
T = 2

For i = FirstRow To LastRow
ArtNum = sh.Cells(i, ArtCol)
CellVal = Application.VLookup(ArtNum, Sheet1.Range(«A1:V306»), T,
False)
If IsError(CellVal) Then
CellVal = «Error»
End If
With sh.Cells(i, «B»)
.Value = CellVal
End With

Advertisements

Howard31


  • #2

When using vlookup, always precede it with the ‘On Error Resume Next’
statement, because if the vlookup does not find a match an error will occure.
In your case because the youre are looping through a range to lookup a
‘ArtNum’ the ‘On Error Resume Next’ statement will cause the code to carry on
to the next cell if it did not find it yet without causing a run-time error.
If it does find a match to ‘ArtNum’ the value of that cell will be asigned to
sh.Cells(i, «B»).Value = CellVal. If it finds it more then once it will asign
the last occurence to sh.Cells(i, «B»).Value = CellVal which is the same
value as before nbeing that youre lookink for the same value. You should
really add the following code which will prevent unnecesary code from running:

If Err.Description = 0 Then ‘ Found match then exit for
Exit For
End If

Hope this helps!

elf27


  • #3

Howard,
Thanks. It wasn’t clear from my code but I am using the For i… because I
want to do this for a number of values in the ArtNum column. Therefore, I
don’t think your exit for code applies.
However, I think you are right on the on error resume next bit. Where should
I put that?
Any other ideas on why it’s not working? I know the data’s in there…

Howard31


  • #4

Put the ‘On Error Resume Next’ as follows:

On Error Resume Next
CellVal = Application.VLookup(ArtNum, Sheet1.Range(«A1:V306»), T, False)

Advertisements

Dave Peterson


  • #5

You shouldn’t have to use «on error resume next» when you use
application.vlookup() in your code. You would need it for
application.worksheetfunction.vlookup(), though.

Where is your code located?

When it was in a general module, it worked fine for me.

What do you have checked (in the VBE):
Tools|Options|General tab|error trapping section
I have «break in class module» checked.

Понравилась статья? Поделить с друзьями:
  • Vlcpulse audio output error pulseaudio server connection failure connection refused
  • Vlc как изменить положение субтитров
  • Vlc как изменить масштаб
  • Vlc socket bind error
  • Vlc sat ip stream error failed to setup rtsp session