Определение с помощью кода VBA Excel, что диапазон ячеек пуст, то есть, ни одна из ячеек диапазона (строки, столбца) не содержит отображаемого значения.
Определение пустого диапазона
Определить в VBA Excel, что диапазон ячеек пуст, можно с помощью функции рабочего листа WorksheetFunction.CountA или свойства диапазона ячеек Range.Text.
Пример 1
Определение, что диапазон ячеек пуст, с помощью функции рабочего листа WorksheetFunction.CountA:
Sub Primer1() If WorksheetFunction.CountA(Range(«A1:L8»)) = 0 Then MsgBox «Диапазон ячеек ««A1:L8»» пуст» Else MsgBox «Диапазон ячеек ««A1:L8»» не пуст» End If End Sub |
Функция WorksheetFunction.CountA подсчитывает количество ячеек, содержащих значения, в том числе нули и формулы, возвращающие пустые строки. Если хотя бы одна ячейка в диапазоне будет содержать пустую строку, возвращенную формулой, то код первого примера определит, что диапазон не пуст.
Пример 2
Определение, что диапазон ячеек пуст, с помощью свойства Text объекта Range:
Sub Primer2() If Range(«A1:L8»).Text = «» Then MsgBox «Диапазон ячеек ««A1:L8»» пуст» Else MsgBox «Диапазон ячеек ««A1:L8»» не пуст» End If End Sub |
Свойство Text объекта Range возвратит пустую строку только в том случае, если все ячейки диапазона будут содержать пустые строки и (или) значение Empty. Если одна или более ячеек в диапазоне будут содержать пустую строку, возвращенную формулой, то код второго примера все-равно определит, что диапазон пуст.
Определение пустой строки
Определение пустой строки в VBA Excel с помощью свойства Range.Text:
Sub Primer3() If Rows(5).Text = «» Then MsgBox «Указанная строка пуста» Else MsgBox «Указанная строка не пуста» End If End Sub |
Данное определение пустой строки используется в коде для удаления пустых строк из таблицы.
Определение пустого столбца
Определение пустого столбца в VBA Excel с помощью свойства Range.Text:
Sub Primer4() If Columns(7).Text = «» Then MsgBox «Указанный столбец пуст» Else MsgBox «Указанный столбец не пуст» End If End Sub |
или
Sub Primer5() If Columns(«G»).Text = «» Then MsgBox «Указанный столбец пуст» Else MsgBox «Указанный столбец не пуст» End If End Sub |
Фразы для контекстного поиска: диапазон пустой, строка пустая, столбец пустой.
how do I check if the string variable is empty in vba?
if:
Dim StrFile1 As String, StrFile2 As String
Dim Text3 As String
Dim Len1 as Integer, Len2 As Integer
With NewMail
Text3 = Cells(i, 3).Value
StrPath = Cells(i, 2).Value & Text3
Text = Cells(i, 1).Value
.Subject =
' adds the data in column3 with space as subject
.From =
.To = Text
.BCC = ""
.TextBody =
StrFile1 = Dir(StrPath & "*.txt")
Len1 = Len(StrFile1)
Do While Len(StrFile1) > 0
.AddAttachment StrPath & StrFile1
StrFile1 = Dir
Loop
StrFile2 = Dir(StrPath & "*.pdf")
Len2 = Len(StrFile2)
Do While Len(StrFile2) > 0
.AddAttachment StrPath & StrFile2
StrFile2 = Dir
Loop
If (Len1 & Len2) = 0 Then
GoTo Last
'.AddAttachment Text3
.Send
End With
i = i + 1
Loop
Last:
End With
i = i + 1
Loop
Now i want to check simultaneously if Len1 and Len2 are 0, if so then I want to go to Last.
When I use this code I get a message/Compile error «Want to end with without with»
and
i am not sure if
If (Len1 & Len2) = 0 Then
GoTo Last
this is a proper code.
and Do i need to declare the label Last??
asked Jun 6, 2016 at 17:14
ShankShank
6533 gold badges9 silver badges21 bronze badges
4
You have many way to do that like below :
Dim StrFiles As String
StrFiles = Trim(StrFile1 & StrFile2)
If IsEmpty(StrFiles) Then
If StrFiles = vbNullString Then
If StrFiles = "" Then
If StrFiles = Empty Then
If Len(StrFiles) = 0 Then
you can use + operator
to check 2 strings are empty reference to your code, because Len Function
returns an integer containing either the number of characters in a string
If (Len1 + Len2) = 0 Then
answered Jun 6, 2016 at 17:28
Abdellah OUMGHARAbdellah OUMGHAR
3,6191 gold badge11 silver badges16 bronze badges
8
You can use Trim(strFile1 & vbNullString) = vbNullString
to check if the string is empty.
So:
If Trim(strFile1 & vbNullString) = vbNullString Then
Debug.print "Empty String!"
End If
Thanks to @LordPeter
answered Jun 6, 2016 at 17:20
BruceWayneBruceWayne
22.8k15 gold badges64 silver badges109 bronze badges
1
is.empty
doesn’t exist for VBA, but the second option works.
Alternatively, you can write:
(strFile1 & strFile2) = vbNullString
or
(strFile1 & strFile2) = ""
answered Jun 6, 2016 at 17:20
basodrebasodre
5,6801 gold badge14 silver badges22 bronze badges
Yet another way is:
If Len(strFile1 & strFile2) > 0 Then
I did test to ensure that strings which aren’t set return a length of 0, which appeared to be the case.
answered Jun 6, 2016 at 17:21
SoulfireSoulfire
4,21821 silver badges32 bronze badges
1
Проверить есть ли в строке данные
|
От: | Аноним | |
Дата: | 15.03.05 06:55 | ||
Оценка: |
Как с помощью vba в Excel таблице проверить является ли данная строка пустой (без данных, без оформления) или нет. Просто мне необходимо проходить все строки таблицы и выдёргивать нужную информацию. Но среди нужных строк иногда попадаются пустые строки, которые нужно игнорировать.
Re: Проверить есть ли в строке данные
|
От: |
Hades |
|
Дата: | 15.03.05 09:03 | ||
Оценка: |
Проверь длину строки, например…
Dim s As String
If (Len(s) <> 0) Then
MsgBox («Кулллл!»)
End If
s = «aaa»
или так:
If (s <> «») Then
MsgBox («Кулллл!»)
End If
Re[2]: Проверить есть ли в строке данные
|
От: | Аноним | |
Дата: | 15.03.05 12:31 | ||
Оценка: |
Здравствуйте, Hades, Вы писали:
Строка — имеется в виду row, т.е. ячейки, расположенные на одинаковом горизонтальном уровне
Re: Проверить есть ли в строке данные
|
От: |
Unforgiver |
|
Дата: | 15.03.05 12:54 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>Как с помощью vba в Excel таблице проверить является ли данная строка пустой (без данных, без оформления) или нет. Просто мне необходимо проходить все строки таблицы и выдёргивать нужную информацию. Но среди нужных строк иногда попадаются пустые строки, которые нужно игнорировать.
Включи обработчик ошибок:
On Error Resume Next
' Делаем операцию со строкой.
On Error Goto 0
Если строка пустая, то с ней ничего не сделается и выполнение пойдет дальше.
Всё заканчивается плохо. Если что-то закончилось хорошо — значит оно еще не закончилось.
Re[3]: Проверить есть ли в строке данные
|
От: |
Elena_ |
|
Дата: | 15.03.05 13:43 | ||
Оценка: |
4 (1) |
Здравствуйте, Аноним, Вы писали:
А>Строка — имеется в виду row, т.е. ячейки, расположенные на одинаковом горизонтальном уровне
Ну если по содержанию ячеек, то перебрать строки можно, например, так
Dim ranRow As Range
For Each ranRow In ActiveSheet.UsedRange.Rows
If Intersect(ranRow, ActiveSheet.UsedRange).Address = _
ranRow.SpecialCells(xlCellTypeBlanks).Address Then
MsgBox ranRow.row & " - Пустая Строка"
Else
MsgBox ranRow.row & " - Непустая Строка"
End If
Next ranRow
А по оформлению, может быть, нужно и смотреть оформление отдельно, надо подумать
Пользователь — друг программиста!
Re: Странные вы какие-то…
|
От: | Аноним | |
Дата: | 16.03.05 12:32 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>Как с помощью vba в Excel таблице проверить является ли данная строка пустой (без данных, без оформления) или нет. Просто мне необходимо проходить все строки таблицы и выдёргивать нужную информацию. Но среди нужных строк иногда попадаются пустые строки, которые нужно игнорировать.
Да чего вы изголяетесь, пробежаться по всем строкам и по всем ячейкам в строке и не париться.
Вот прмер отчёта в Intermediate о «путотости»/»непустотости» каждой строки в активном листе:
Option Explicit
Public Sub RowsCheck()
Dim clsRow As Excel.Range
Dim clsCell As Excel.Range
Dim clsActiveSheet As Excel.Worksheet
Dim blnEmpty As Boolean
Set clsActiveSheet = ActiveSheet
For Each clsRow In clsActiveSheet.Rows
blnEmpty = True
''''''''''''''''''''''''''''''''''''''
'Тут проверяешь каждую строку в листе.
For Each clsCell In clsRow.Cells
'''''''''''''''''''''''''''''''''''''''
'Тут проверяешь каждую ячейку в строке.
If Not VBA.IsEmpty(clsCell.Value) Then
blnEmpty = False
Exit For
End If
Next clsCell
If blnEmpty Then
Debug.Print "Row:""" & clsRow.Address & """ Is Empty"
Else
Debug.Print "Row:""" & clsRow.Address & """ Is Not Empty"
End If
Next clsRow
End Sub
PS: Задолбаетесь ждать, пока макрос отработает — жмите {Ctrl}+{Pause|Break}. Это я так, на всяк…
Re[2]: Странные вы какие-то…
|
От: |
Elena_ |
|
Дата: | 16.03.05 13:49 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>Да чего вы изголяетесь, пробежаться по всем строкам и по всем ячейкам в строке и не париться.
А>Вот прмер отчёта в Intermediate о «путотости»/»непустотости» каждой строки в активном листе:
А>
А> For Each clsRow In clsActiveSheet.Rows
А> blnEmpty = True
А> ''''''''''''''''''''''''''''''''''''''
А> 'Тут проверяешь каждую строку в листе.
А> For Each clsCell In clsRow.Cells
А> '''''''''''''''''''''''''''''''''''''''
А> 'Тут проверяешь каждую ячейку в строке.
А> If Not VBA.IsEmpty(clsCell.Value) Then
А> blnEmpty = False
А> Exit For
А> End If
А> Next clsCell
А>
Но зачем проверять даже те ячейки, которые не попали в UsedRange?
Зачем проверять каждую ячейку, если можно проверить сразу диапазон?
Пользователь — друг программиста!
|
От: | Аноним | |
Дата: | 18.03.05 13:44 | ||
Оценка: |
Здравствуйте, Elena_, Вы писали:
E_>Но зачем проверять даже те ячейки, которые не попали в UsedRange?
E_>Зачем проверять каждую ячейку, если можно проверить сразу диапазон?
Согласен, но тогда «отмажусь» нехваткой времени ==> сыростью программы.
+ тут уже есть пример с использованием UserRange.
PS: В 97’м ёкселе (были слухи что и в 2000’м) «SpecialCells(xlCellTypeBlanks)» не всегда корректно работает…
|
От: |
Elena_ |
|
Дата: | 18.03.05 20:35 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>PS: В 97’м ёкселе (были слухи что и в 2000’м) «SpecialCells(xlCellTypeBlanks)» не всегда корректно работает…
В общем-то, если пустых ячеек совсем нет, то действительно некорректно получается
Я имела в виду, чтобы не перебирать по ячейке, так как при больших объемах это все-таки будет заметно
Можно еще, например,
Dim ranRow As Range
For Each ranRow In ActiveSheet.UsedRange.Rows
If Application.WorksheetFunction.CountBlank(ranRow.EntireRow) = 256 Then
MsgBox ranRow.Row & " - Пустая Строка"
Else
MsgBox ranRow.Row & " - Непустая Строка"
End If
Next ranRow
Пользователь — друг программиста!
- Переместить
- Удалить
- Выделить ветку
Пока на собственное сообщение не было ответов, его можно удалить.
*Note:* This post was originally posted on my blog. I hope posting it here will help reach those whom it will help.
Recently I have been using VBA for a project in Excel and, though I know what I want to express in VBA, I don’t always know the syntax since it isn’t my main programming language. I had to look up the syntax for the if / else conditional clause and how to check whether a string variable is empty. Given that I’m an experienced software engineer and still had to look them up I thought sharing them with you here would be helpful.
Note: Don’t just copy and paste before reading the article. Copying and pasting without understanding is unwise. You do so at your own danger.
If – Then – Else Conditional Statements In VBA
The if – else conditional statement is a staple of any programming language. In each language they have the same meaning. That is if some condition is true then take some action. Otherwise do something else or skip the action. Each language, however, has a slightly different way of saying this; that is each language has a different syntax.
In the case of VBA this is handled as follows (and as described in this guide on Microsoft’s docs website. The documentation is here):
If [condition] Then
' code
ElseIf [condition] Then
' code
Else
' code
End If
Checking String Variables For Emptiness
There are two common checks needed when dealing with data coming from a source outside the control of code you’re writing. These are:
- Did I get data or is it empty?
- Does the data conform to what I expect and can deal with?
In the case of the code I was writing I’ve got a class with member variables some of which are optional. When I am going to use them to pass the data on I need to know if there is data present to decide what to do with them. The last piece of pertinent information is that I am treating all the variables as strings because I will be sending the data over an API.
Can We Use The IsEmpty() function?
My initial search for how to check whether a string is empty led me to the IsEmpty() function. This seems like a really good fit for what I was looking for. As described in the documentation:
Returns a Boolean value indicating whether a variable has been initialized.
Given that I want to check whether a member variable of my class has been initialized to a value this looks like exactly what I want. As I was about to write this, however, I thought it would be a good idea to test this just to make sure that I am giving you correct information. As such, I wrote this small bit of code:
Sub CheckVarForEmpty()
Dim stringVar As String
If IsEmpty(stringVar) = True Then
MsgBox "Variable Is Empty!"
End If
End Sub
After writing this I ran this fully expecting to have a message box pop up saying that the variable is empty. However it did NOT pop up.
VBA Debugger To The Rescue!
However, when I debugged the code to make sure that the message box was really being skipped, I noticed that the variable showed that it had the value “”. Now, to me, this looks like an empty string but I decided to write another conditional testing the value of the string against “”:
Sub CheckVarForEmpty()
Dim stringVar As String
If stringVar = "" Then
MsgBox "Varable Is = to Empty String"
End If
End Sub
Sure enough the message box is shown. Hooray! This means that checking a string against “” successfully determines if a string variable is empty.
Why Didn’t IsEmpty() Work?
However, because I was curious I why IsEmpty() did not return true in my first attempt, I went back to the documentation and read it again. It specifically says that IsEmpty() only returns True if a variable is not initialized or explicitly set to Empty. If you notice in my first example I declare stringVar as a string because I am used to programming in strongly typed languages and it makes sense to me to mark how a variable is to be used. Given that the documentation for IsEmpty() shows examples where the variables were NOT declared with types. This made me wonder if, by declaring a variable with a type, it initializes it to a value (“” in the case of strings). This would make IsEmpty() return False. As such I wrote another test to see if this train of thought is valid:
Sub CheckVarForEmpty()
Dim myVar
If IsEmpty(myVar) = True Then
MsgBox "MyVar is Empty!"
End If
End Sub
Sure enough the message box in this test popped up as the documentation indicated it would. This, for me, confirms that declaring a variable in VBA as a particular type will initialize it in a manner appropriate for that type.
Conclusion — I always have more to learn
This exercise shows that, despite my years of experience, there are always more things to learn. I hope that this helps you in your adventures in VBA. For me, the next things I will teach myself regarding VBA is more about how classes are constructed and destructed. I hope to bring you more knowledge as I gain it for myself.
Note. Check if the TextBox1
is empty is easy by using TextBox1.Value = ""
.
But the problem is when the user hit the spacebar
, TextBox1
will still recognize it as a value. In such case, my data will appear as an empty cell with 1 space
inside. So my question is, is there any method to check TextBox1.value
for empty and also not consist of space
whether there are 1 or more space
? Million thanks to all.
asked Jan 1, 2013 at 8:15
4 Leave Cover4 Leave Cover
1,21812 gold badges39 silver badges81 bronze badges
A common trick is to check like this:
trim(TextBox1.Value & vbnullstring) = vbnullstring
this will work for spaces, empty strings, and genuine null values
answered Jan 1, 2013 at 8:18
4
Most terse version I can think of
Len(Trim(TextBox1.Value)) = 0
If you need to do this multiple times, wrap it in a function
Public Function HasContent(text_box as Object) as Boolean
HasContent = (Len(Trim(text_box.Value)) > 0)
End Function
Usage
If HasContent(TextBox1) Then
' ...
answered Jan 1, 2013 at 8:38
pyrospadepyrospade
7,7703 gold badges36 silver badges52 bronze badges
4
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
nateAtwork
1681 gold badge4 silver badges13 bronze badges
answered Jan 1, 2013 at 8:21
6
You can use the following code to check if a textbox object is null/empty
'Checks if the box is null
If Me.TextBox & "" <> "" Then
'Enter Code here...
End if
Thomas G
9,7167 gold badges29 silver badges40 bronze badges
answered Apr 24, 2016 at 12:46
0