Excel vba if value is text

Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

  • #2

You can check for numbers using IsNumeric.

  • #3

You can check for numbers using IsNumeric.

Thank You

I tried this and it gave me a 7 or 8. I believe 7 might be a date and 8 a string. Is there a way i can display it as Date rather 7 and String rather than 8?

Code:

Sub test()
 
For Each cell In Sheets("sheet1").Range("A1:A10")
    MsgBox VarType(cell)
Next
 
End Sub

Is there a difference between VarType and Typename?

Last edited: Apr 15, 2012

  • #4

Try TypeName.

By the way to check for dates you can use IsDate.

Oh, almost forgot, if the value us text but can be recognised as a date then IsDate will return True.

The same applies for IsNumber.

  • #5

Try TypeName.

By the way to check for dates you can use IsDate.

Oh, almost forgot, if the value us text but can be recognised as a date then IsDate will return True.

The same applies for IsNumber.

Thank you.

Now that might be a problem (the value is text but can be recognised as a date then IsDate will return True)

I have some dates that look like dates but are actually strings.

I need to check to see if the value is a string/date/number etc?

If it is a String, is there a quick way to change string values to Date and vice versa?

  • #6

Is there a problem with having ‘text’ dates?

What is it you are trying to do?

  • #7

Is there a problem with having ‘text’ dates?

What is it you are trying to do?

Hi, my aim is to convert every dates that entered as text to actual dates
Any numbers that have been entered as text as numbers

Hope this makes sense. I want a vba solution to do this.

I guess i wanted to see the values which were extracted incorrectly and wanted to see the type but i guess thats not required.

  • #8

Just add 0 to all the values.

If they are text that will convert it to a number/date and if they are already number/date they won’t be changed.

You would want to avoid blank cells though as if you add 0 to a blank the result is 0.

  • #9

I think it might be something to do with text to columns ( I need it in VBA).

I have recorded via macro recorder and the it works fine however….

I am not sure about these 4 lines of the code

TextQualifier:=xlDoubleQuote, _ what is the DoubleQuote text qualifier?
ConsecutiveDelimiter:=False, _ ???
FieldInfo:=Array(1, 3), _ ???
TrailingMinusNumbers:=True ???

I have tried to read through the help but still not getting it :(

I am not sure how to perform this for All my data rather than just the first column. I have 8 columns of data

Last edited: Apr 15, 2012

  • #10

Add 0 to all the values using PasteSpecial>Operations add which you can do using code.

Code:

Cells(1, Columns.Count).Copy
 
Range("A1:H1000").PasteSpecial Operation:=xlPasteSpecialOperationAdd

EXPLANATION

This tutorial shows how to test if a cell contains text and return a specified value if the test is True or False by using Excel formulas or VBA.

This tutorial provides three Excel methods that can be applied to test if a cell contains text.

The first method uses a combination of an Excel IF and ISTEXT functions. The ISTEXT function test if the selected cell contains text. If it does then the function will return a TRUE value. The IF function is then used to return a specified value if the ISTEXT function returns a value of TRUE, which in this example is «Contains Text». Alternatively, if the ISTEXT function returns a value of FALSE, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

The second method uses a combination of an Excel IF and ISNUMBER functions. The ISNUMBER function test if the selected cell is a numeric value. If the cell is a numeric value, meaning that there are no text values, then the function will return a TRUE value, alternatively if the cell contains a text value, the function will return a FALSE value. The IF function is then used to return a specified value if the ISNUMBER function returns a value of FALSE, which in this example is «Contains Text». Alternatively, if the ISNUMBER function returns a value of TRUE, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

The third method uses a combination of an Excel IF and COUNTIF functions. The COUNTIF function uses the «*» to identify if the cell contains text. If the cell contains text the COUNTIF function will return a value of 1, alternatively it will return a value of 0. The IF function is then used to return a specified value if the COUNTIF function returns a value greater than 0, which in this example is «Contains Text». Alternatively, if the COUNTIF function returns a value of 0, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

This tutorial provides six VBA methods that can be applied to test if a cell contains text and return a specific value. Methods 1, 3 and 5 are applied against a single cell, whilst methods 2, 4 and 6 use a For Loop to loop through all of the relevant cells, as per the example in the image, to test each of the cells in a range and return specific values. The main difference between the examples is how the code determines is the cell contains text.

FORMULA (using ISTEXT function)
=IF(ISTEXT(value)=TRUE, value_if_true, value_if_false)

FORMULA (using ISNUMBER function)
=IF(ISNUMBER(value)=FALSE, value_if_true, value_if_false)

FORMULA (using COUNTIF function)
=IF(COUNTIF(value, «*»)>0, value_if_true, value_if_false)

ARGUMENTS
value: The value or cell that is to be tested.
value_if_true: Value to be returned if the value or cell contains text.
value_if_false: Value to be returned if the value or cell does not contains text.

 

Здравствуйте!  
Вопрос, по сути в заголовке.    
Имеем значения, к примеру: «345» и «3куц» как в коде проще всего определить что можно использовать как число?    
Чет я простых методов не нашел… :(

 

LightZ

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

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

Может я что-то не правильно понял?  
Debug.Print IsNumeric(Cells(1, 1).Value)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Понял ошибку. Я пробовал  Is Numeric.  
Спасибо!

 

LightZ

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

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

Не за что  
Также:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

Контакты см. в профиле

{quote}{login=LightZ}{date=09.07.2012 07:29}{thema=}{post}Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»){/post}{/quote}С этим нужно осторожнее: при пустом значении и дате, получим неверные ответы :-)

 

Ну мне для решения конкретной задачи больше всего походит первый вариант в виде:  
If IsNumeric(Arr(i)) Then a = a + Arr(i)

 

ZVI

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

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

Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»)

 

KuklP

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

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

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

Здравствуйте все. В дополнение, и это тоже:  
Debug.Print Application.IsText(«1d3»), Application.IsText(«1e2»)  
:-)

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

 

KuklP

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

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

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

Забыл еще:  
Debug.Print Application.IsText(«13»), Application.IsText(«12»)

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

 

LightZ

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

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

Так я думаю вряд ли кто-то будет использовать  
с перемененными и константами всё Ок  

  Const x As Long = «111»: Const z As String = «abc»  
Debug.Print Application.IsText(x), Application.IsText(z)  

  False True

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

KuklP

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

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

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

Богдан, вот это — неправильно:  
Const x As Long = «111»  
Правильно:  
Const x As Long = 111  
Экс, да, произведет неявное преобразование, что не есть хорошо. Из-за того, что результат в разных случаях непредсказуем и может привести к ошибкам выполнения:-)  
Попробуй по шагам:  
Const x As Long = «1d3»  
Stop  
И посмотри, чему равен х.

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

 

LightZ

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

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

Серёж, а в чём разница то?  

  Const x As Long = «111»  
Const x As Long = 111

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

Контакты см. в профиле

«111» — строка  
111 — число

 

{quote}{login=ZVI}{date=09.07.2012 09:56}{thema=}{post}Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»){/post}{/quote}  
А почему к «d» и «e» такое «избранное» отношение?  
Проверил другие буквы — везде False

 

LightZ

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

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

{quote}{login=Юрий М}{date=09.07.2012 11:37}{thema=}{post}»111″ — строка  
111 — число{/post}{/quote} Ну это если не объявлять числовую переменную, тогда так

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

Контакты см. в профиле

Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.

 

> А почему к «d» и «e» такое «избранное» отношение?  

  Михаил, это экспоненциальная запись числа. 1d3=1000, 1e2=100.  
В Фортране использование символа E означает тип Single, а D — Double. То есть там 1 — единица целого типа, 1E0 — единица типа Single, 1D0 — единица типа Double.  
VBA воспринимает обе буквы как указание типа Double.  
Попробуйте также в окне Immediate  

  ?isnumeric(«ff»),isnumeric(«&hff»),isnumeric(«&o75»),isnumeric(«&o79»)

 

Я попробовал так: хоть 234е765б + 1 хоть 123d765 + 1 =11 (+25 = 35)  
и вообще, т.е если внутри цифр, сколько бы из не было, стоит одна е или d, то как число это равно 10. но цифры должны быть с обеих сторон.

 

k61

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

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

IsNumeric(«ЧислоИлиЦифра» & Chr(160) & «ЧислоИлиЦифра»)=True  
Chr(160) — пробел.

 

Если данные будут считываться только из ячеек рабочего_листа:  

  Function ValueIsNumber(X) As Boolean  
   Select Case VarType(X)  
   Case vbDouble, vbDate, vbBoolean  
   Case Else  
       Exit Function  
   End Select  
   ValueIsNumber = True  
End Function  

  Если даты или логические не считать числами — удалить vbDate или vbBoolean

 

LightZ

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

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

{quote}{login=Юрий М}{date=10.07.2012 10:40}{thema=}{post}Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.{/post}{/quote}Юрий, я понял.  
По идее в варианте Михаила, данные будут заливаться с листа, т.е. проблем с IsNumeric или же IsText возникнуть не должно, у меня всегда отрабатывали на ура. :)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

Контакты см. в профиле

Если других данных не будет, то всё нормально. Весь сыр-бор разгорелся из-за того, что с проверкой типа есть подводные камни, и их желательно учитывать.

 

LightZ

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

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

Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет (false)  

  Dim x As Range  
   For Each x In ActiveSheet.UsedRange  
       If Not Application.Trim(x.Value) = Empty Then Debug.Print IsNumeric(x.Value), x.Value, x.Address  
   Next

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

ran

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

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

Что-то я не улавливаю.  
Если x.Value = Empty, то зачем Application.Trim ?  
Если x.Value <> Empty, то Application.Trim(x.Value) все равно не будет Empty

 

Юрий М

Модератор

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

Контакты см. в профиле

{quote}{login=LightZ}{date=10.07.2012 10:01}{thema=}{post}Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет {/post}{/quote}Ну как же нет?  
Вот Ваше предложение:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Введите в ячейку дату и проверьте.

 

ZVI

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

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

E — это экспоненциальная форма записи числа  
D — это тоже какая-то архаичная форма числа.  
И то и другое выдаст число As Double, возможно поэтому и D  

  В окне Immediate:  
?2d3 или ?2e3 покадут результат 2000, т.е 2*10^3  
?VarType(2e3)=vbDouble выдаст True  

  Если вписать в VBA-модуле, например, такую строку:  
a = 2d3 или a = 2e3  
то после смещения курсора на другую строку эта преобразуется в    
a = 2000#  
где # в конце означает преобразование числа в Double

 

Павел

Гость

#27

10.07.2012 22:23:57

2 Михаил С  

Цитата
А почему к «d» и «e» такое «избранное» отношение

Точка и знаки «d» и «e» могут быть частью записи числа, не поэтому ли?

 

LightZ

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

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

RAN, воспроизведите макрос:  
Sub tt()  
   With Cells(1, 1)  
       .Value = »   »  
       Debug.Print .Value = Empty, Application.Trim(.Value) = Empty  

                 .Value = Empty  
       Debug.Print .Value = Empty  
   End With  
End Sub  

  Т.е. с помощью Application.Trim(x.Value) убиваю сразу двух зайцев: пустоту и пробел  

  Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату  

     With Cells(1, 1)  
       If Not IsDate(.Value) Then Debug.Print Application.IsText(.Value)  
   End With

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

Контакты см. в профиле

{quote}{login=LightZ}{date=10.07.2012 10:29}{thema=}{post}Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату{/post}{/quote}Я реагировал на это:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Посмотрите — моё сообщение сразу после Вашего :-) Разобрались :-)

 

Михаил С.

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

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

#30

10.07.2012 23:15:44

Такой, казалось бы, простой вопрос, а столько подводных камней! :)  
Для моей задачи подошел самый первый ответ — IsNumeric(a).  
По сути у меня массив примерно 150 столбцов, с столбцы и числовые и тестовые. Нужно строки, удовлетворяющие определенным условиям, сложить, пропуская тест.  
такой кусок кодаЖ  
For ii =  1 To Ubound(Arr, 2)  
if IsNumeric(Arr(i, ii)) Then MiArr(si, ii) = MiArr(si, ii)+Arr(i, ii)  
Next  
Дат у меня нет, но проверил ради интереса — обрабатывает корректно, т.е. пропускает

В языке VBA есть универсальные типы данных, т.е. способные хранить как число, так и строку, дату и любой другой тип информации. Например, ячейка в таблице может содержать что угодно и изначально, программа не знает какой в ней тип данных хранится. Кроме того, в самой программе может использоваться тип данных Variant, который так же может содержать любое значение любого типа.

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

Способ 1. Использовать функцию TypeName для определения типа данных

Эта функция возвращает строку с названием типа данных на английском. В качестве аргумента принимает переменную, значение ячейки.
Обратите внимание: Функция определяет только стандартные типы данных и не может определить пользовательский тип (определенный с помощью Type).

Возможные возвращаемые функцией значения:

Byte Число типа Byte
Integer Целое число
Long Длинное целое число
Single Число одиночной точности с плавающей запятой
Double Число двойной точности с плавающей запятой
Currency Валюта
Decimal Число с плавающей запятой
Date Дата
String Строка
Boolean Логическое
Error Ошибка
Empty Не проинициализировано (т.е. переменная не была объявлена)
Null Неверные данные (в переменной нет корректных данных)
Object Объект (класс)
Unknown Тип данных не известен
Nothing Объект, никуда не ссылающийся

Приведу несколько примеров по использованию TypeName.

Пример 1. Определение типа переменной.

Dim v As Integer
MsgBox TypeName(v) ' Выведет: Integer

Обратите внимание: если вы используете результат TypeName в условии, т.е. проверяете, соответствует ли тип данных определенному, например, Integer, то регистр символов возвращаемого типа имеет значение. Т.е. нужно писать Integer с заглавной буквы, либо использовать приведение всех символов к одному регистру.

Пример 2. Использование TypeName в условии.

Dim v As Integer
If TypeName(v) = "Integer" Then MsgBox "Yes" Else MsgBox "No"         ' Yes
If TypeName(v) = "integer" Then MsgBox "Yes" Else MsgBox "No"         ' No
If LCase(TypeName(v)) = "integer" Then MsgBox "Yes" Else MsgBox "No"  ' Yes

Пример 3. Определение типа данных в ячейке.

MsgBox TypeName(Cells(1, 1).Value) ' Выведет тип данных в ячейке A1

Если функции была передана переменная массив, она вернет тип данных в массиве с добавлением скобок.

Пример 4. Определение типа массива.

Dim Arr1(10) As Integer
Dim Arr2(10)
MsgBox TypeName(Arr1) ' Выведет: Integer()
MsgBox TypeName(Arr2) ' Выведет: Variant()

Способ 2. Проверка на возможность преобразования строки к нужному типу.

Бывает ситуация, когда значение, например, число или дата, содержится в строке. В этом случае TypeName вернет String, а не Integer или Date. Чтобы узнать, что содержится в строке, можно воспользоваться одной из функций IsNumeric, IsDate, IsObject, IsArray, IsNull, IsError.

IsNumeric Проверяет может ли выражение быть преобразовано в число
IsDate Проверяет может ли выражение быть преобразовано в дату
IsObject Проверяет, является ли переменная объектом
IsArray Проверяет, является ли переменная массивом
IsNull Проверка на пустое значение
IsError Проверка выражения на ошибку

Пример 4. Определение может ли переменная быть преобразована в число.

Dim v As String
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no (т.к. в строке нет числа)
v = "120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
v = "120.45"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "test 120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "120 test"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

К сожалению, как видим из примера, нет возможности проверить, содержится ли в строке число с плавающей точкой.

Пример 5. Определение содержит ли переменная дату (может быть преобразована в дату).

Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
firstDate = CDate("12.05.2017")
secondDate = #12/5/2017#
timeOnly = "15:45"
dateAndTime = "12.05.2017 15:45"
noDate = "Test"
If IsDate(firstDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(secondDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(timeOnly) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(dateAndTime) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(noDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

Проверка, содержится ли число или дата в ячейке листа делается аналогично, как и с переменными.

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

Skip to content

Excel Logo

Excel If Cell Contains Text

Excel If Cell Contains Text Then

Excel If Cell Contains Text Then Formula helps you to return the output when a cell have any text or a specific text. You can check if a cell contains a some string or text  and produce something in other cell. For Example you can check if a cell A1 contains text ‘example text’  and print Yes or No in Cell B1. Following are the example Formulas to check if Cell contains text then return some thing in a Cell.

If Cell Contains Text

Here are the Excel formulas to check if Cell contains specific text then return something. This will return if there is any string or any text in given Cell. We can use this simple approach to check if a cell contains text, specific text, string,  any text using Excel If formula. We can use equals to  operator(=) to compare the strings .

If Cell Contains Text Then TRUE

Following is the Excel formula to return True if a Cell contains Specif Text. You can check a cell if there is given string in the Cell and return True or False.

=IF(ISNUMBER(FIND(“How”,A1,1)),TRUE,FALSE)

The formula will return true if it found the match, returns False of no match found.

If Cell Contains Text Then TRUE

If Cell Contains Partial Text

We can return Text If Cell Contains Partial Text. We use formula or VBA to Check Partial Text in a Cell.

Find for Case Sensitive Match:

We can check if a Cell Contains Partial Text then return something using Excel Formula. Following is a simple example to find the partial text in a given Cell. We can use if your want to make the criteria case sensitive.

=IF(ISERROR(FIND($E$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text

  • Here, Find Function returns the finding position of the given string
  • Use Find function is Case Sensitive
  • IsError Function check if Find Function returns Error, that means, string not found

Search for Not Case Sensitive Match:

We can use Search function to check if Cell Contains Partial Text. Search function useful if you want to make the checking criteria Not Case Sensitive.

=IF(ISERROR(SEARCH($F$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text Not Case Sensitive

If Range of Cells Contains Text

We can check for the strings in a range of cells. Here is the formula to find If Range of Cells Contains Text. We can use Count If Formula to check the excel if range of cells contains specific text and return Text.

=IF(COUNTIF(A2:A21, “*Region 1d*”)>0,”Range Contais Text”,”Text Not Found in the Given Range”)
  • CountIf function counts the number of cells with given criteria
  • We can use If function to return the required Text
  • Formula displays the Text ‘Range Contains Text” if match found
  • Returns “Text Not Found in the Given Range” if match not found in the specified range

If Cells Contains Text From List

Below formulas returns text If Cells Contains Text from given List. You can use based on your requirement.

VlookUp to Check If Cell Contains Text from a List:
We can use VlookUp function to match the text in the Given list of Cells. And return the corresponding values.

  • Check if a List Contains Text:
    =IF(ISERR(VLOOKUP(F1,A1:B21,2,FALSE)),”False:Not Contains”,”True: Text Found”)
  • Check if a List Contains Text and Return Corresponding Value:
    =VLOOKUP(F1,A1:B21,2,FALSE)
  • Check if a List Contains Partial Text and Return its Value:
    =VLOOKUP(“*”&F1&”*”,A1:B21,2,FALSE)

If Cell Contains Text Then Return a Value

We can return some value if cell contains some string. Here is the the the Excel formula to return a value if a Cell contains Text. You can check a cell if there is given string in the Cell and return some string or value in another column.

If Cell Contains Text Then Return a Value

=IF(ISNUMBER(SEARCH(“How”,A1,1)),”Found”,”Not Found”)

The formula will return true if it found the match, returns False of no match found. can

Excel if cell contains word then assign value

You can replace any word in the following formula to check if cell contains word then assign value.

=IFERROR(IF(SEARCH(“Word”,A2,1)>0,1,0),””)

Excel if cell contains word then assign value
Search function will check for a given word in the required cell and return it’s position. We can use If function to check if the value is greater than 0 and assign a given value (example: 1) in the cell. search function returns #Value if there is no match found in the cell, we can handle this using IFERROR function.

Count If Cell Contains Text

We can check If Cell Contains Text Then COUNT. Here is the Excel formula to Count if a Cell contains Text. You can count the number of cells containing specific text.

=COUNTIF($A$2:$A$7,”*”&D2&”*”)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then COUNT

Count If Cell Contains Partial Text

We can count the cells based on partial match criteria. The following Excel formula Counts if a Cell contains Partial Text.

=COUNTIF(A2:A21, “*Region 1*”)
  • We can use the CountIf Function to Count the Cells if they contains given String
  • Wild-card operators helps to make the CountIf to check for the Partial String
  • Put Your Text between two asterisk symbols (*YourText*) to make the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to make the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to make the criteria to find your text end of given Cell

If Cell contains text from list then return value

Here is the Excel Formula to check if cell contains text from list then return value. We can use COUNTIF and OR function to check the array of values in a Cell and return the given Value. Here is the formula to check the list in range D2:D5 and check in Cell A2 and return value in B2.

=IF(OR(COUNTIF(A2,”*”&$D$2:$D$5&”*”)), “Return Value”, “”)

Excel If cell contains text from list then return value

If Cell Contains Text Then SUM

Following is the Excel formula to Sum if a Cell contains Text. You can total the cell values if there is given string in the Cell. Here is the example to sum the column B values based on the values in another Column.

=SUMIF($A$2:$A$7,”*”&D2&”*”,$B$2:$B$7)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then SUM

Sum If Cell Contains Partial Text

Use SumIfs function to Sum the cells based on partial match criteria. The following Excel formula Sums the Values if a Cell contains Partial Text.

=SUMIFS(C2:C21,A2:A21, “*Region 1*”)
  • SUMIFS Function will Sum the Given Sum Range
  • We can specify the Criteria Range, and wild-card expression to check for the Partial text
  • Put Your Text between two asterisk symbols (*YourText*) to Sum the Cells if the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to Sum the Cells if the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to Sum the Cells if criteria to find your text end of given Cell

VBA to check if Cell Contains Text

Here is the VBA function to find If Cells Contains Text using Excel VBA Macros.

If Cell Contains Partial Text VBA

We can use VBA to check if Cell Contains Text and Return Value. Here is the simple VBA code match the partial text. Excel VBA if Cell contains partial text macros helps you to use in your procedures and functions.

Sub sbCkeckforPartialText()
MsgBox CheckIfCellContainsPartialText(Cells(2, 1), “Region 1”)
End Sub
Function CheckIfCellContainsPartialText(ByVal cell As Range, ByVal strText As String) As Boolean
If InStr(1, cell.Value, strText) > 0 Then CheckIfCellContainsPartialText = True
End Function
  • CheckIfCellContainsPartialText VBA Function returns true if Cell Contains Partial Text
  • inStr Function will return the Match Position in the given string

If Cell Contains Text Then VBA MsgBox

Here is the simple VBA code to display message box if cell contains text. We can use inStr Function to search for the given string. And show the required message to the user.

Sub sbVBAIfCellsContainsText()
If InStr(1, Cells(2, 1), “Region 3”) > 0 Then blnMatch = True
If blnMatch = True Then MsgBox “Cell Contains Text”
End Sub
  • inStr Function will return the Match Position in the given string
  • blnMatch is the Boolean variable becomes True when match string
  • You can display the message to the user if a Range Contains Text

Which function returns true if cell a1 contains text?

You can use the Excel If function and Find function to return TRUE if Cell A1 Contains Text. Here is the formula to return True.

=IF(ISNUMBER(FIND(“YourText”,A1,1)),TRUE,FALSE)

Which function returns true if cell a1 contains text value?

You can use the Excel If function with Find function to return TRUE if a Cell A1 Contains Text Value. Below is the formula to return True based on the text value.

=IF(ISNUMBER(FIND(“YourTextValue”,A1,1)),TRUE,FALSE)

Share This Story, Choose Your Platform!

7 Comments

  1. Meghana
    December 27, 2019 at 1:42 pm — Reply

    Hi Sir,Thank you for the great explanation, covers everything and helps use create formulas if cell contains text values.

    Many thanks! Meghana!!

  2. Max
    December 27, 2019 at 4:44 pm — Reply

    Perfect! Very Simple and Clear explanation. Thanks!!

  3. Mike Song
    August 29, 2022 at 2:45 pm — Reply

    I tried this exact formula and it did not work.

  4. Theresa A Harding
    October 18, 2022 at 9:51 pm — Reply
  5. Marko
    November 3, 2022 at 9:21 pm — Reply

    Hi

    Is possible to sum all WA11?

    (A1) WA11 4

    (A2) AdBlue 1, WA11 223

    (A3) AdBlue 3, WA11 32, shift 4

    … and everything is in one column.

    Thanks you very much for your help.

    Sincerely Marko

  6. Mike
    December 9, 2022 at 9:59 pm — Reply

    Thank you for the help. The formula =OR(COUNTIF(M40,”*”&Vendors&”*”)) will give “TRUE” when some part of M40 contains a vendor from “Vendors” list. But how do I get Excel to tell which vendor it found in the M40 cell?

    • PNRao
      December 18, 2022 at 6:05 am — Reply

      Please describe your question more elaborately.
      Thanks!

© Copyright 2012 – 2020 | Excelx.com | All Rights Reserved

Page load link

Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.

Проверка переменных и выражений

Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.

Синтаксис функций для проверки переменных и выражений:

Expression — выражение, переменная или необязательный аргумент для IsMissing.

Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.

Функция IsArray

Описание функции

Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:

  • True — переменная является массивом;
  • False — переменная не является массивом.

Пример с IsArray

Sub Primer1()

Dim arr1(), arr2(1 To 10), arr3

    Debug.Print IsArray(arr1)  ‘Результат: True

    Debug.Print IsArray(arr2)  ‘Результат: True

    Debug.Print IsArray(arr3)  ‘Результат: False

arr3 = Array(1, 2, 3, 4, 5)

    Debug.Print IsArray(arr3)  ‘Результат: True

End Sub

Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.

Функция IsDate

Описание функции

Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:

  • True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
  • False — в иных случаях.

Пример с IsDate

Sub Primer2()

Dim d1 As String, d2 As Date

    Debug.Print IsDate(d1)  ‘Результат: False

    Debug.Print IsDate(d2)  ‘Результат: True

d1 = «14.01.2023»

    Debug.Print IsDate(d1)  ‘Результат: True

    Debug.Print IsDate(Now)  ‘Результат: True

End Sub

Функция IsEmpty

Описание функции

Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:

  • True — переменная содержит значение Empty;
  • False — переменной присвоено значение, отличное от Empty.

Пример с IsEmpty

Sub Primer3()

Dim s As String, v As Variant

    Debug.Print IsEmpty(s)  ‘Результат: False

    Debug.Print IsEmpty(v)  ‘Результат: True

v = 125

    Debug.Print IsEmpty(v)  ‘Результат: False

Range(«A1»).Clear

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: True

Range(«A1») = 123

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: False

End Sub

Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).

Функция IsError

Описание функции

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

  • True — аргумент функции является значением ошибки, определенной пользователем;
  • False — в иных случаях.

Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.

Пример с IsError

Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:

Function Vkuba(x)

    If IsNumeric(x) Then

        Vkuba = x ^ 3

    Else

        Vkuba = CVErr(25)

    End If

End Function

Sub Primer4()

    Debug.Print Vkuba(5)  ‘Результат: 125

    Debug.Print IsError(Vkuba(5))  ‘Результат: False

    Debug.Print Vkuba(«пять»)  ‘Результат: Error 25

    Debug.Print IsError(Vkuba(«пять»))  ‘Результат: True

End Sub

Функция IsMissing

Описание функции

Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:

  • True — если в процедуру не было передано значение для необязательного аргумента;
  • False — значение для необязательного аргумента было передано в процедуру.

Пример с IsMissing

Function Scepka(x, Optional y)

    If Not IsMissing(y) Then

        Scepka = x & y

    Else

        Scepka = x & » (а необязательный аргумент не подставлен)»

    End If

End Function

Sub Primer5()

    Debug.Print Scepka(«Тропинка», » в лесу»)  ‘Результат: Тропинка в лесу

    Debug.Print Scepka(«Тропинка»)  ‘Результат: Тропинка (а необязательный аргумент не подставлен)

End Sub

Функция IsNull

Описание функции

Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:

  • True — значением переменной или выражения является Null;
  • False — в иных случаях.

Пример с IsNull

Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:

Sub Primer6()

Dim Var

Var = Null

    If Var = Null Then Debug.Print Var  ‘Результат: «»

    If Var <> Null Then Debug.Print Var  ‘Результат: «»

    If IsNull(Var) Then Debug.Print Var  ‘Результат: Null

End Sub

Функция IsNumeric

Описание функции

Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:

  • True — если аргумент функции может рассматриваться как число;
  • False — в иных случаях.

Пример с IsNumeric

Sub Primer7()

Debug.Print IsNumeric(«3,14»)  ‘Результат: True

Debug.Print IsNumeric(«четыре»)  ‘Результат: False

End Sub

Функция IsObject

Описание функции

Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:

  • True — переменная содержит ссылку на объект или значение Nothing;
  • False — в иных случаях.

Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.

Пример с IsObject

Sub Primer8()

Dim myObj As Object, myVar As Variant

    Debug.Print IsObject(myObj)  ‘Результат: True

    Debug.Print IsObject(myVar)  ‘Результат: False

Set myVar = ActiveSheet

    Debug.Print IsObject(myVar)  ‘Результат: True

End Sub


Vba Format Cell If Is Text And Not A Numeric Value — Excel

Hi all,

I am currently using the below VBA code to do a conditional format with more than 3 options, and it is working fine.

What I would like to add is an operator to check if the cell is text instead of a number, and if so format in a different colour (ie Black background and white text). This should overide all other formatting if the cell contains text.

Any suggestions on what to use? I am thinking an isnum type function but not too familiar with the VBA coding equivalent.

My current code is:

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim MyRange As Range, cell As Range
Set MyRange = Range("b2:m35")
For Each cell In MyRange
    
        If cell.Value <= [i38].Value Then
            cell.Interior.ColorIndex = 3
        End If
        
        If cell.Value >= [f38].Value Then
            cell.Interior.ColorIndex = 45
        End If
                
        If cell.Value >= [d38].Value Then
            cell.Interior.ColorIndex = 27
        End If
                
        If cell.Value >= [b38].Value Then
            cell.Interior.ColorIndex = 4
        End If
        
        If cell.Value = "" Then
            cell.Interior.ColorIndex = 2
        End If
        
    Next
    
End Sub

Thanks

Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

(80% Discount Ends Soon!)

View Course


Similar Topics



I’m using some basic code below in an on Workbook Open event to format cells with a value less then 2 and less than 1 with a particular color.

The code works, but it really slows my worksheet down when opening. Is there better way to write this? Thanks!

Code:

 
Dim myRange As Range
Dim cell As Range
Set myRange = Range("V6:V50000")
    For Each cell In myRange
    If cell.Value < 2 Then cell.Font.ColorIndex = 5
    If cell.Value < 1 Then cell.Font.ColorIndex = 3
    Next

View Answers


Corporate edict.

I have a worksheet that is locked and protected now, except for cells in a certain collumn. I have named the cells in that column «MS96A».

If a user enters a date in a cell or range of cells anywhere in the column, the changed cells also need to be locked and protected (Once they enter a date, it is not allowed EVER to be changed again. Corporate requirement! *Shrug*).

What I am looking for is this. If the user selects that cell again, they will get the usual pop-up message, «The cell or chart that you are trying to change is protected…»

I think I am close, but I am getting an «End If without block If» error on the If Clause.

Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim MRange As Range
Set MRange = Range(«MS96A»)
‘ If Not Intersect(Target, MRange) Is Nothing Then
For Each cell In MRange
Sheets(«Sheet1″).Unprotect Password:=»temp»
cell.Interior.ColorIndex = 3
cell.Font.Color = vbBlack
Selection.Locked = True
Selection.FormulaHidden = False

Next cell

ActiveSheet.Protect Password:=»temp», _
DrawingObjects:=False, _
Contents:=True, _
Scenarios:=False
ActiveSheet.EnableSelection = xlUnlockedCells

End Sub

View Answers


Hi everyone,

I’m going nuts trying to figure out how to autofill text from one cell
to another. For example, everytime I type text into cell A20, I want
the exact same thing to cell BL20. The same for B20, BL20, etc.

How do I go about that? I already know how to copy formulas from one
cell to another by dragging the skinny black line of the cell. I guess
I just need the formula for a simple IDENTICAL copying of text.

Thanks in advance,

Mike

View Answers


I am looking for assistance in having one cell in a text format equals another cell that contains a time value in hh:mm format.

For example: Cell A1 has a time format (hh:mm) value of 04:00; which is the Start Time. I would like cell D1 to have a text format value of «04:00» (result is dependant upon what is entered in A1). I would duplicate the same formulas to reflect Stop Times in other cells.

My final result is to have another cell (F1) use the Concatenate formula to have the Start and Stop time shown in one cell as «04:00 — 12:30». The times would change based on the Time formated values entered into the Start and Stop time cells.

I have researched this in the board and found many excellent ways to do the opposite, but not convert Time format to Text format. Any assistance is greatly appreciated.

-Shane

View Answers


Hi, this is something so simple that I have forgotten how to do it.
I want F3 to turn yellow if someone selects «Yes» from a drop down list in cell E3, then F3 has no fill once data is entered into it. And F3 turns Black if E3= no selected from the list. Or F3 turns red if E3 contains «TBC»

so in summary,

if E3=»Yes», then F3 conditional format to Yellow until data is entered in it.
if E3=»No», then F3 conditional format to Black
if E3=»TBC», then E3 & F3 conditional format to Red until E3 is changed to
«Yes» or «No» at a later time.

Thanks in Advance for the help

Mutley13

View Answers


I have been using Excel (XP) to make a text chart for several months. Some of
my text entries are rather lengthy. The past two weeks these lengthy entries
are showing up as pound signs (#########) when I click off the cell. I know
the text will fit in the cell, and the problem isn’t solved by making the
cell bigger or using a little bit less text. I have the cells formatted as
«text» and «wrap to fit». I have printed the pages and the printed version
also has pound signs. I just want my text to show up!

View Answers


I want to Sum Column «H» starting form «H2» all the way down (rows may vary)
Then Paste My answer in «AM1»
This is what I have so far and for some reason is not working.

Code:

myRange = ActiveSheet.Range("H2", Range("H2").End(xlDown))
Range("AM1") = WorksheetFunction.Sum(myRange)

Any Ideas?

View Answers


Is there a way I can use conditional formatting or something to change the color of the cell once I enter a value or text into that cell? For example if I currently have the A2 cell color as a gray color, and I enter information into A2 can I have it set to automatically change to no fill or any other color without having to click out of the cell, back into it, and then clicking the button?? Does that make sense??? Can someone help me?

View Answers


I saw two threads in this forum that asked this question, with no good answer. I am posting this solution for anybody still struggling with this.

The question:
How can you prevent a cell’s contents from overflowing into the next cell?

Of course, you can make the column wider or turn on text wrapping, but you might not want to. Each of those solutions can mess up the layout of your sheet. You may just want to truncate the value.

Some people have suggested putting a space in the next cell. This is unnecessary, a pain in the but, and will mess up any ISBLANK type formulas, among other things.

The solution:
Select the cells in question and turn on text wrapping (Format>Cells>Alignment>Wrap Text).
Now select the row(s) in question and manually set the row height, by right clicking the row number and selecting «Row Height». Check the height of an adjacent row for a good value.

Your cells will now not spill over either horizontally or vertically. They will simply truncate anything that doesn’t fit.

Be careful now, because parts of your data may be hidden. This can cause its own set of problems if one or two digits are neatly hidden away. Think ahead if other people might be using this sheet, and not be expecting to have some data hidden.

Tested in Excel 2002

View Answers


I have cells in a column, some colored yellow, some not. I am trying to use
the SUMIF function to sum only the cells in the range that are colored. Can
this be done? Can I enter something in the «criteria» part of the formula
that can do this?

=SUMIF(D3:D13,»criteria»,D3:D13)

I also tried to use the CELL function’s color feature, but I couldn’t get it
to work right. I don’t know how to get Excel to recognize if a cell is
colored in a formula.
=CELL(«color»,cell)

It might just be that I don’t know what this means in Help:

«color» —> 1 if the cell is formatted in color for negative values;
otherwise returns 0 (zero).

Can anyone help?

View Answers


Hi all —

Im very familiar with how to write a macro to automatically autofilter a list based upon a Cell Value (i.e. Range =(A1)…etc.)…. but what I cannot figure out how to correctly write is a way to have Excel automatically autofilter a list for any row that CONTAINS the Cell Value, instead of just the exact value.

Cell Value = «birds»
Example — I need to filter every row so that I see every row that CONTAINS «birds» in the character-string, not just the row that = «birds».

a) is this possible?

If not, I’d like to know also so I can stop attempting to guess (-;
Thanks!!!

Matt

View Answers


Hi guys,

would really appreciate anyones help with this.

I have a column full of text-formatted fractions…

4/5
6/4
3/1
2/5
4/5

etc, etc…..the column is very long!!

I need to convert these to actual fractions…ones I can add to equations, allowing me to multiply and add.

If I highlight the column and goto «format Cells» and change to fraction, the values still stay in the left of the cell…..its only when I manually click on each individual cell, then tick the little green tick, does the cell validate, and the value in the cell moves to the right (and is therefore a proper value)…..problem is I have to keep doing this for each individual cell…..and I have 70000+ cells in this column!

Any suggestions on how I could speed this up?

thanks

View Answers


Hello,

I am new to using Excel and I am not very computer literate. I am looking for some help with a spreadsheet I am making. Here is the problem:

I have a column of 14 numbers in cells A1 to A14. If all of these values are less than 2%, I would like a «Pass» to display in cell B1. If any of these values are greater than 2% I would like a «Fail» to display in cell B1.

I have got a formula that works for a single cell but I can’t figure out how to get it to apply to more than one cell. For example, I have entered =IF(A1<2,»Pass»,»Fail») in cell B1. Now if the value I enter in A1 is less than 2, it shows a «Pass», and if the value in A1 is greater than 2 it shows a «Fail» in cell B1. How can I get this to apply to all of the cells from A1 to A14?

If somebody could help me out that would be great.

Thanks,
Randy

View Answers


I would like to create a formula that removes a specific character if it appears in a cell. In this case, if the text in the name cell starts with * or #, remove it. Otherwise, keep the contents intact. Examples:

Code:

Text in Cell     Desired Results
*Bobby Abreu      Bobby Abreu
#Erick Aybar      Erick Aybar
Jason Bartlett    Jason Bartlett

Is there a formula that will get me where I want to be?

Thanks!

Chuck

View Answers


I was wondering if anyone could help me out please?!?!

I need to have a cell on Sheet2 display the TEXT from a cell on Sheet1, is his possible??

Example:

Sheet1, Cell A1 contains a clients name and I would like to have Sheet2, Sheet3, Sheet4 etc… Display that clients name in a cell of my choosing (could be a different cell on each Sheet) automatically after entering it once on Sheet1, cell A1.

I thought this was possible but I can’t seem to figure it out. I haven’t done any real Excel work in quite a long time but I thought I had done this before a long time ago!! Any help would be GREATLY appreciated!! Thanks in advance…

P.S. If I use autosum to do this it just displays the number 0, obviously, since it is trying to add numbers…

I uploaded a copy of the spreadsheet, What I would like to happen is have the text from Sheet1,D4 automatically be placed in Sheet2,A1 and Sheet3, B2. Hope this helps

-Aric

View Answers


I have an extensive spreadsheet with several columns and all showing borders
where each cell/column begins and ends. However there are a few cells where
the break with the next cell does not show the line.

I have highlighed the cell in question, gone to format/cell/borders and
everything looks fine. Black color + format border shows square with all
sides of square showing.

Any thoughts on how to fix these few random cells.

Thanks

View Answers


Hi everyone, this is my first post here. I consider myself a more advanced Excel user and can navigate my way around fairly well. I’ve written a spreadsheet and am wondering if there is a way to permit data entry in a cell, contingent upon another cell being populated.

In simple terms, you can’t enter data in cell X, until cell «Y» has been populated with something.

Can anyone help with this, because I can’t figure it out….

View Answers


I am trying to establish a formula, but not too sure how.

For example » If Cell A5 has been marked with ‘ X ‘, then copy what is in Cell A6 to

cell C25 «

View Answers


Hello All

I wonder if you could help with this one, I have a list of data like this (no spaces or other characters)

JN551122B

What I need to do is split each of the characters in to its own cell

if JN551122B was in cell A1 I’d want to return:

B2 C2 D2 E2 F2 G2 H2 I2 J2
J N 5 5 1 1 2 2 B

The nearest I have got is the right function, but it brings over the preceeding characters, and I need each character in its own cell. Hopefully I could copy/paste a formula and change the reference for each cell value, i.e. 1 would return J, 2 = N, 3 = 5, 4 = 5 etc.

Thanks for your help!

View Answers


I have a textbox in my userform where anything typed in the box is entered into cell A2 in my worksheet. However, multiple lines of text are not properly displayed in my worksheet. I have enabled MultiLine and EnterKeyBehaviour in the properties window of the textbox so I can type multiple lines in my textbox. The problem is that when I press the button to enter the text from my txtbox to cell A2, the cell doesn’t actually display the text in separate lines. It just places a square symbol in the place that enter should have been pressed and the text should have been split into separate lines.

How can I get the separate lines of text in my textbox to be properly displayed in a cell? Thanks for your help in advance..

View Answers


Проверка типов данных (числовых и текстовых) (Visual Basic for Applications)

Иногда появляются ошибки при вводе данных. Наиболее неприятные это случайный ввод букв вместо цыфр, портятся все вычисления, если они есть для данной ячейки. Поэтому считаю актуальным делать для некоторых полей вот такие две проверки:

1. Программа для проверки «Вводятся ли положительные числовые данные?»

Private Sub TextBox1_Change()

If TextBox1.Value < 0 Then

MsgBox «Числа не должны быть отрицательными!», vbOKOnly + vbInformation, «Error»

TextBox1.SetFocus

End If

If Not IsNumeric(TextBox1.Text) And Len(TextBox1) <> 0 Then

MsgBox «Вводить необходимо числовые данные», vbOKOnly + vbInformation, «Error»

TextBox1.Value = «»

TextBox1.SetFocus

End If

End Sub

2. Программа для проверки «Вводятся ли текстовые данные?»

Private Sub TextBox3_Change()

If IsNumeric(TextBox3.Text) And Len(TextBox3) <> 0 Then

MsgBox «Вводить надо текстовые данные!», vbOKOnly + vbInformation, «Error@»

TextBox3.Value = » «

TextBox3.SetFocus

End If

End Sub

Пояснения:

SetFocus – устанавливает фокус на вызвавшем этот метод элементе управления (в данном примере на TextBox). Часто применяется в программах обработки ошибок

IsNumeric – функция проверки типов – является ли переменная числовым значением

Len – возвращает число символов строки

Понравилась статья? Поделить с друзьями:
  • Excel vba if value is date
  • Excel vba if value is a number
  • Excel vba if then with or
  • Excel vba if then else and or
  • Excel vba if textbox1