Excel vba is nothing is not nothing

Return to VBA Code Examples

This tutorial will demonstrate how to use the Is Nothing statement in VBA

The VBA Is Nothing statement uses the VBA “Is” Operator and checks to see an object has been assigned to an object variable.

Sub CheckObject
Dim rng as Range
If rng Is Nothing then
  Msgbox "Range not assigned"
End If
End Sub

We can also use Not with Is Nothing with an If statement to make sure that a Range has been assigned to the range variable we declared and then run the code that we wish to run if that variable has been assigned.

Sub CheckAssignedObject
  Dim rng as Range
  Set rng = Range("A1:A6")
  If Not rng Is Nothing then
    '' do some code here
  End If
End Sub

We can use the Is Nothing statement for any type of object.  It can be extremely useful in preventing errors in our code where an object might not be assigned to an object variable.

For example, we can use a worksheet variable, and assign it to the Active Sheet.  If we do this successfully, then we can select A2 in that sheet.

Sub CheckWorksheetObject 
Dim ws as Worksheet
Set ws = ActiveSheet
If Not ws Is Nothing then 
   ws.Range("A2").Select
End If
End Sub

In the code above, the cell A2 will be selected.  If we were to remove the line  “Set ws=ActiveSheet“, then the If statement would bypass that line of code and cell A2 would not be selected.

Is Nothing can also be used in other Microsoft Office applications such as PowerPoint, Outlook, Access and Word.  The following code checks to see if the Document Object has been assigned to the Active Word Document.

Sub CheckDocumentObject
Dim wdDoc as Document
Set wdDoc = ActiveDocument
If wdDoc Is Nothing then
  MsgBox "Document not assigned"
Else
  MsgBox "Document assigned"
End If
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

ТС написал  
>>Есть переменная Ws связанное с листом книги Set Ws=activesheet , потом возможно книга с листом Ws будет закрыто что я и пытаюсь определить через If Ws is Nothing Then bla-bla-bla но это условие не срабатывает(((<<  

  Макросом я смоделировал эту ситуацию. Думаю моя описка, написал pSheet Is Nothing, вместо pSheet Is Not Nothing, не меняяет смысла этой ситуации.  

  Не думаю, что столь уважаемые люди The_Prist, Юрий М не видят, что ТС прав.  
То есть в макросе создаётся книга. Устанавливается переменная pSheet  на активный лист этой книги. Далее, книга закрывается, но VBA не устанавливает эту переменную в Nothing. Следовательно, используя If pSheet Is Nothing, нельзя установить дейстительна ли ссылка на лист или нет. И утверждение «If Ws is Nothing Then не будет в описанном случае выдавать ошибку» является неверным.

  1. Feb 19th, 2008, 04:26 PM


    #1

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Resolved [RESOLVED] correct usage of «Is Not Nothing»

    What’s the correct syntax/usage of this line:

    If frmForm1 Is Not Nothing Then ..etc.

    I keep getting «Invalid use of object» error.

    Really what I’m trying to say in code is:
    1)if frmForm1 is not unloaded yet then etc.. do stuff

    2)So if the Form is unloaded, don’t do anything — skip the lines of code

    Thanks


  2. Feb 19th, 2008, 04:30 PM


    #2

    Re: correct usage of «Is Not Nothing»

    It’s like this:

    If Not (frmForm1 Is Nothing) Then


  3. Feb 19th, 2008, 04:31 PM


    #3

    Re: correct usage of «Is Not Nothing»

    Just like it would be for an = rather than an ‘Is’, ie:

    Code:

    If Not frmForm1 Is Nothing Then

    («Not» is effectively the same as «=False», so what you had was basically the same as: «If frmForm1 Is (Nothing=False) Then» )


  4. Feb 19th, 2008, 04:33 PM


    #4

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Re: correct usage of «Is Not Nothing»


  5. Feb 19th, 2008, 04:33 PM


    #5

    Re: correct usage of «Is Not Nothing»

    If that does not work, then try this:

    Code:

    Public Function IsFormLoaded(FormName As String) As Boolean
        Dim Frm As Form
        
        For Each Frm In Forms
            If LCase(Frm.Name) = LCase(FormName) Then
                IsFormLoaded = True
                Exit Function
            End If
        Next Frm
    End Function
    
    If Not IsFormLoaded("frmForm1") Then ...

    I’m posting that because sometimes by just checking if the form is loaded you load the form
    So the function does not load the form un-intentionally


  6. Feb 19th, 2008, 04:45 PM


    #6

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Re: correct usage of «Is Not Nothing»

    Hey

    It does the code either way.

    I clearly: UnLoad Me (my splash page)

    but it is doing the code that should only execute when the Splash form is Loaded and Shown.

    thanks


  7. Feb 19th, 2008, 05:01 PM


    #7

    Re: [RESOLVED] correct usage of «Is Not Nothing»

    A form will automatically re-load itself if you run any code which refers to it (or the controls on it), or if it has a Timer control which you have not turned off.

    Note that generally you should have «Exit Sub» immediately after «Unload Me», and should always disable Timer controls in the _Unload event of the form.


  8. Feb 19th, 2008, 05:01 PM


    #8

    Re: [RESOLVED] correct usage of «Is Not Nothing»

    The simple act of checking if a Form Is Nothing will Initialize (but not Load) the Form. If frmForm1 is the actual name of a Form then the statement If Not frmForm1 Is Nothing will always be True.


  9. Feb 19th, 2008, 05:21 PM


    #9

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Re: [RESOLVED] correct usage of «Is Not Nothing»

    Si, you’re absolutely right, I am running code which refers to the splash page.
    I did «Exit Sub» immediately after «Unload Me», and disabled the Timer and it is still displaying the Splash page after the app has started. I’ll give CV’s code a try and post back.

    CJ


  10. Feb 19th, 2008, 05:32 PM


    #10

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Re: [RESOLVED] correct usage of «Is Not Nothing»

    None of it is working as expected. THanks , when I figure it out, I’ll post for others.

    CJ


  11. Feb 19th, 2008, 05:38 PM


    #11

    CyberJar is offline

    Thread Starter


    Hyperactive Member


    Re: [RESOLVED] correct usage of «Is Not Nothing»

    OK, somehow this works using the Function CV suggested:

    If IsFormLoaded(«frmForm1») Then

    Happy Days
    CJ


  12. Feb 2nd, 2016, 04:43 AM


    #12

    newuserforum is offline


    New Member


    Re: [RESOLVED] correct usage of «Is Not Nothing»

    Hello everyone!
    I have a problem with VBA for Excel .
    I want to search for a specific value(for a specific ID) in a column of a sheet and pass the value in another table row (of that ID).
    What happens If the value in the What:=»value» parameter of the Find() method doesn’t exists for all the IDs in the column?
    If the ID (of the first sheet) doesn’t have that value I dont want to pass any value to the other sheet (of that ID).I want to set a «#N/A» value instead
    In fact it passes the value of the predecessor ID.
    What should I do.


  13. Feb 2nd, 2016, 05:19 AM


    #13

    Re: [RESOLVED] correct usage of «Is Not Nothing»

    You’ve asked your question in 7 year old thread that has nothing to do with your question and is in the VB6 section when your question is about VBA.

    Might I suggest that posting your question in a new thread, with an appropriate title, in the correct forum (which would be Office Development in this case) is likely to get you a better response.

    In the meantime I’ll close this thread so that it can sink back into the murky depths from which it has been roused.

    The best argument against democracy is a five minute conversation with the average voter — Winston Churchill

    Hadoop actually sounds more like the way they greet each other in Yorkshire — Inferrd


Содержание

  1. Ключевое слово Nothing (Visual Basic)
  2. Комментарии
  3. VBA is Nothing
  4. VBA Coding Made Easy
  5. VBA Code Examples Add-in
  6. VBA If Is Nothing
  7. 1 Answer 1
  8. Vba excel проверка nothing

Ключевое слово Nothing (Visual Basic)

Представляет значение по умолчанию для любого типа данных. Для ссылочных типов значением по умолчанию является null ссылка. Для типов значений значение по умолчанию зависит от того, допускает ли тип значения значение NULL.

Для типов значений, не допускающих значение NULL, Nothing в Visual Basic отличается от null в C#. В Visual Basic, если для переменной типа Nothing , не допускающего значение NULL, задано значение , переменной присваивается значение по умолчанию для объявленного типа. В C# при присвоении переменной типа null , не допускающего значение NULL , возникает ошибка во время компиляции.

Комментарии

Nothing представляет значение по умолчанию для типа данных. Значение по умолчанию зависит от того, имеет ли переменная тип значения или ссылочный тип.

Переменная типа значения напрямую содержит ее значение. Типы значений включают все числовые типы данных, Boolean , , Date Char , все структуры и все перечисления. Переменная ссылочного типа сохраняет ссылку на экземпляр объекта в памяти. Ссылочные типы включают классы, массивы, делегаты и строки. Дополнительные сведения см. в разделе Типы значений и ссылочные типы.

Если переменная имеет тип значения, поведение Nothing зависит от того, имеет ли переменная тип данных, допускающий значение NULL. Чтобы представить тип значения, допускающий значение NULL, добавьте ? модификатор к имени типа. При присвоении Nothing переменной, допускающей значение NULL, устанавливается значение null . Дополнительные сведения и примеры см. в разделе Типы значений, допускающих значение NULL.

Если переменная имеет тип значения, не допускающий значения NULL, при присвоении Nothing ей присваивается значение по умолчанию для объявленного типа. Если этот тип содержит переменные-члены, все они имеют значения по умолчанию. В следующем примере это показано для скалярных типов.

Если переменная имеет ссылочный тип, присваивание Nothing переменной присваивает ей ссылку null на тип переменной. Переменная, для которую задана null ссылка, не связана ни с каким объектом . Следующий пример демонстрирует это:

При проверке того, является ли переменная ссылочной (или допускающей значение NULL) переменной null , не используйте = Nothing или <> Nothing . Всегда используйте Is Nothing или IsNot Nothing .

Для строк в Visual Basic пустая строка равна Nothing . Таким образом, «» = Nothing имеет значение true.

В следующем примере показаны сравнения, использующие операторы Is и IsNot :

Если объявить переменную без использования As предложения и присвоить Nothing ей значение , переменная имеет тип Object . Примером этого является Dim something = Nothing . Ошибка времени компиляции возникает в этом случае, когда Option Strict включен и Option Infer отключен.

При назначении Nothing объектной переменной она больше не ссылается ни на один экземпляр объекта. Если переменная ранее ссылалась на экземпляр, установка для нее Nothing значения не завершает работу самого экземпляра. Экземпляр завершается, а связанные с ним ресурсы памяти и системы освобождаются только после того, как сборщик мусора обнаружит, что не осталось активных ссылок.

Nothing отличается от DBNull объекта , который представляет неинициализированный вариант или несуществующий столбец базы данных.

Источник

VBA is Nothing

This tutorial will demonstrate how to use the Is Nothing statement in VBA

The VBA Is Nothing statement uses the VBA “Is” Operator and checks to see an object has been assigned to an object variable.

We can also use Not with Is Nothing with an If statement to make sure that a Range has been assigned to the range variable we declared and then run the code that we wish to run if that variable has been assigned.

We can use the Is Nothing statement for any type of object. It can be extremely useful in preventing errors in our code where an object might not be assigned to an object variable.

For example, we can use a worksheet variable, and assign it to the Active Sheet. If we do this successfully, then we can select A2 in that sheet.

In the code above, the cell A2 will be selected. If we were to remove the line “Set ws=ActiveSheet“, then the If statement would bypass that line of code and cell A2 would not be selected.

Is Nothing can also be used in other Microsoft Office applications such as PowerPoint, Outlook, Access and Word. The following code checks to see if the Document Object has been assigned to the Active Word Document.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA If Is Nothing

I want to test an object to see if it doesn’t exist. If it does not exist, I just want to have a MsgBox show up (or write Error in cell A1 or something). Banana does not exist in this XML.

Why does this block not do anything? I feel like it’s being completely overlooked at by VBA. I even tried putting an End in the If statement.

Also, the error is also thrown at the print range line.. which is in the If Not Author Is Nothing statement. Very strange.

1 Answer 1

The reason your loop is still executing is simply that If Author Is Nothing evaluates as true. The call to XMLFile.SelectNodes returns an IXMLDOMNodeList, which is an enumerable container. In fact, the reason that it can be used with For Each syntax depends on this. In general, any enumeration returned by a function will give you an enumerable with no items in it rather than a null object. The For Each syntax is equivalent to doing this:

For Each just has the benefit of being more readable.

The error you get actually isn’t related to the question you’re asking, and correcting the check on the return value of XMLFile.SelectNodes(«/catalog/book/banana») won’t solve the error if you don’t get any results. The error lies in trying to use your arrays after the loop if they aren’t instantiated (although the added End would have solved that).

When you exit the loop and get here.

. your AuthorArray and BookTypeArray have only been initialized if you’ve been through the loop, because you are relying on the ReDim Preserve in the Sub AddValue to initialize them. This has 2 solutions. You can either put an Exit Sub in your test of the return value:

Or you can initialize the arrays at the start of the function.

This also has the added benefit of allowing you to skip all of the hoops in your array resizing to determine if they have been initialized. Split(vbNullString) will return an array with a UBound of -1 ( MyVariantArray = Array() will do the same for arrays of Variant). That allows you to rewrite Sub AddValue like this:

Finally, I’d take @SOofXWLS’s suggestion and @barrowc’s suggestions and use explicit object types since you are late binding. That way your IntelliSense will show auto-complete lists at very least. If you don’t know what types of objects are returned, just hit F2 for the Object Browser and check:

If you don’t know where to even start with a new object model, you can also use this quick and dirty trick.

Источник

Vba excel проверка nothing

Sub tt()
Dim sh As Worksheet, wsDataSheet As Object, lLastrow As Long
Dim iCell As Range, iCell1 As Range, i As Long, iCell2 As Range, iCell3 As Range
Dim iSearchText$, iSearchText1$
‘——————————————————————————————————-
iSearchText$ = «Номер один*»
iSearchText1$ = «Номер Два»
Set wsDataSheet = ActiveWorkbook.Sheets(«Вывод»)
‘——————————————————————————————————-
lLastrow = wsDataSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
For Each sh In Worksheets
If sh.Name = wsDataSheet.Name Then GoTo Point
‘——————————————————————————————————-
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
‘——————————————————————————————————-
If Not iCell Is Nothing Then
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 6)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 3)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
‘——————————————————————————————————-
wsDataSheet.Cells(lLastrow, 1).Value = iCell
wsDataSheet.Cells(lLastrow, 2).Value = iCell1
wsDataSheet.Cells(lLastrow, 3).Value = iCell2
wsDataSheet.Cells(lLastrow, 4).Value = iCell3
lLastrow = lLastrow + 1
End If
‘——————————————————————————————————-
Point:
Next sh

без него вылезает ошибка 91
просто хочу понять и прошу мне такому не догоняющему объяснить. чтобы применять с умом

Sub tt()
Dim sh As Worksheet, wsDataSheet As Object, lLastrow As Long
Dim iCell As Range, iCell1 As Range, i As Long, iCell2 As Range, iCell3 As Range
Dim iSearchText$, iSearchText1$
‘——————————————————————————————————-
iSearchText$ = «Номер один*»
iSearchText1$ = «Номер Два»
Set wsDataSheet = ActiveWorkbook.Sheets(«Вывод»)
‘——————————————————————————————————-
lLastrow = wsDataSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
For Each sh In Worksheets
If sh.Name = wsDataSheet.Name Then GoTo Point
‘——————————————————————————————————-
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
‘——————————————————————————————————-
If Not iCell Is Nothing Then
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 6)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 3)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
‘——————————————————————————————————-
wsDataSheet.Cells(lLastrow, 1).Value = iCell
wsDataSheet.Cells(lLastrow, 2).Value = iCell1
wsDataSheet.Cells(lLastrow, 3).Value = iCell2
wsDataSheet.Cells(lLastrow, 4).Value = iCell3
lLastrow = lLastrow + 1
End If
‘——————————————————————————————————-
Point:
Next sh

без него вылезает ошибка 91
просто хочу понять и прошу мне такому не догоняющему объяснить. чтобы применять с умом Elhust

Каждый сам выбирает правила игры

Ответить

Sub tt()
Dim sh As Worksheet, wsDataSheet As Object, lLastrow As Long
Dim iCell As Range, iCell1 As Range, i As Long, iCell2 As Range, iCell3 As Range
Dim iSearchText$, iSearchText1$
‘——————————————————————————————————-
iSearchText$ = «Номер один*»
iSearchText1$ = «Номер Два»
Set wsDataSheet = ActiveWorkbook.Sheets(«Вывод»)
‘——————————————————————————————————-
lLastrow = wsDataSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
For Each sh In Worksheets
If sh.Name = wsDataSheet.Name Then GoTo Point
‘——————————————————————————————————-
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole)
‘——————————————————————————————————-
If Not iCell Is Nothing Then
Set iCell = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 6)
Set iCell1 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 3)
Set iCell2 = sh.UsedRange.Find(What:=iSearchText$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
Set iCell3 = sh.UsedRange.Find(What:=iSearchText1$, LookIn:=xlValues, LookAt:=xlWhole).Offset(0, 1)
‘——————————————————————————————————-
wsDataSheet.Cells(lLastrow, 1).Value = iCell
wsDataSheet.Cells(lLastrow, 2).Value = iCell1
wsDataSheet.Cells(lLastrow, 3).Value = iCell2
wsDataSheet.Cells(lLastrow, 4).Value = iCell3
lLastrow = lLastrow + 1
End If
‘——————————————————————————————————-
Point:
Next sh

без него вылезает ошибка 91
просто хочу понять и прошу мне такому не догоняющему объяснить. чтобы применять с умом Автор — Elhust
Дата добавления — 14.04.2017 в 08:15

Источник

Gudvin
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 13.07.2004 (Вт) 13:23
  • ICQ

Как проверить не равен ли объект Nothing?

IsNull и IsEmpty дают false при проверке Объекта с Nothing. Как проверить то?


alibek
Большой Человек
Большой Человек
 
Сообщения: 14205
Зарегистрирован: 19.04.2002 (Пт) 11:40
Откуда: Russia

Сообщение alibek » 15.07.2004 (Чт) 11:16

If MyObj Is Nothing Then …

Lasciate ogni speranza, voi ch’entrate.


Gudvin
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 13.07.2004 (Вт) 13:23
  • ICQ

Сообщение Gudvin » 15.07.2004 (Чт) 11:18

Спасибо тебе, большой человек! :D Без поллитры…



Вернуться в VBA

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1

Понравилась статья? Поделить с друзьями:
  • Excel vba number format number
  • Excel vba is not numeric
  • Excel vba is keyword
  • Excel vba now time
  • Excel vba is decimal