Vba excel if not isnumeric

Проверка переменных и выражений с помощью встроенных функций 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


 

Артем Кузнецов

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

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

#1

17.08.2020 22:13:57

Уважаемые знатоки, подскажите пожалуйста, почему у меня а макросе функция IsNumeric не понимает что выбраны числа? код и файл прилагается …

Код
'Находит по строкам в каждой строке максимальное и минимальное значение и выводит результат в 10 столбец
Sub Массив_Макс_Мин()
Dim myArray()
Dim i As Long
Dim j As Long
Dim max As Long
Dim min As Long
Dim myCell As Variant

On Error Resume Next    'что бы не вылетала ошибка при нажатии на Esc или Отмена
Set myCell = Application.InputBox("Выделите числовой диапазон", Type:=8)       'выделние ячеек через InputBox

If myCell.Count = 1 Then
MsgBox "Выделите диапазон"
Else
Call Массив_Макс_Мин_Вызов
If IsNumeric(myCell) Then
Call Массив_Макс_Мин_Вызов
Else
MsgBox "Выделите числа"
End If
End If
End Sub

Sub Массив_Макс_Мин_Вызов()
Dim myArray()
Dim i As Long
Dim j As Long
Dim max As Long
Dim min As Long
Dim myCell As Range

myArray = myCell.Value
For i = 1 To UBound(myArray, 1)
    max = myArray(i, 1)
    min = myArray(i, 1)
    For j = 1 To UBound(myArray, 2)
        If myArray(i, j) > max Then
            max = myArray(i, j)
        ElseIf myArray(i, j) < min Then
            min = myArray(i, j)
        End If
    Next j
    Cells(i, 10).Value = "max" & " " & max & " " & "min" & " " & min
Next i
Set myCell = Nothing        'освобождение памяти, желательно делать для всех Set
End Sub

Прикрепленные файлы

  • 1.xlsm (24.04 КБ)

 

не понимает если шагом ранее выбрано что?

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Hugo

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

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

IsNumeric анализирует одно значение, а не сразу много ячеек.

 

а как тогда задать условие для диапазона что если выбраны не числа то ничего не делать, или exit sub или еще что? везде пишут про функцию IsNumeric для чисел  …

 

Проверять каждую ячейку по отдельности, в цикле.

 

БМВ

Модератор

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

Excel 2013, 2016

#6

18.08.2020 07:11:00

Код
If WorksheetFunction.CountIf(myCell, "?*") = 0 Then

Но вы не пишете «1» это число или это цифра (знак)?

Изменено: БМВ18.08.2020 07:12:08

По вопросам из тем форума, личку не читаю.

 

Артем Кузнецов

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

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

#7

19.08.2020 01:25:45

чего то все равно не работает

Код
If myCell.Count = 1 Then 
MsgBox "Выделите диапазон" 
ElseIf myCell.CountIf(myCell, "?*") = 0 Then 
MsgBox "Выделите числовой диапазон" 
Else Call Массив_Макс_Мин_Вызов 
End If

и такой вариант myCell.NumberFormat = «@»подсмотренный здесь же на форуме тоже не выполняется …..

Изменено: Артем Кузнецов19.08.2020 01:39:54

 

Артем Кузнецов

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

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

#8

19.08.2020 01:27:20

Цитата
БМВ написал:
о вы не пишете «1» это число или это цифра (знак)?

у меня на листе во вложенном файле вроде как это числа, формата — общий  

 

Михаил О.

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

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

#9

19.08.2020 01:50:10

Код
Sub Массив_Макс_Мин()
    Dim myCell As Variant

    On Error Resume Next
    Set myCell = Application.InputBox("Выделите числовой диапазон", Type:=8)
    If TypeName(mycell) <> "Range" Then Exit Sub
    On Error GoTo 0
    
    If myCell.Count = 1 Then
        MsgBox "Выделите диапазон", vbExclamation, "Внимание"
        Exit Sub
    End If
    
    Dim Val As Variant
    For Each Val In myCell
        If Not IsNumeric(Val) Then
            MsgBox "Выделите числа", vbExclamation, "Внимание"
            Exit Sub
        End If
    Next Val
    
    Call Массив_Макс_Мин_Вызов
    
End Sub

Изменено: Михаил О.19.08.2020 14:52:29

Я не Михаил…

 

БМВ

Модератор

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

Excel 2013, 2016

#10

19.08.2020 07:06:50

Цитата
Артем Кузнецов написал:
чего то все равно не работает

А должно? Найдите отличия между

Цитата
БМВ написал:
WorksheetFunction.CountIf(myCell, «?*») = 0

и

Цитата
Артем Кузнецов написал:
myCell.CountIf(myCell, «?*») = 0

Про числа и цифры я о том, что если есть вероятность появления текста в виде «1» или «10», то это текст или нужно преобразовать в число?

Изменено: БМВ19.08.2020 07:10:13

По вопросам из тем форума, личку не читаю.

 

sokol92

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

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

Здравствуйте, Михаил! Не знал (или забыл?) этот трюк с COUNTIF. :)

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

Изменено: sokol9219.08.2020 13:29:21

 

Здравствуйте, Михаил не работает и ваш вариант, только в случае указания одной ячейки пишет выделите диапазон, в остальных случаях вылетает ошибка Type Missmatch …

 

Артем Кузнецов

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

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

#13

19.08.2020 14:41:32

Цитата
БМВ написал:
А должно? Найдите отличия между

а я и так и так писал в результате и так и так не работает, ну excel считает запись «2» текстом, значит логично что наверное это должен быть текст, зачем текст воспринимать как число, если с ним все равно никаких  вычислений нельзя сделать …

 

БМВ

Модератор

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

Excel 2013, 2016

sokol92, Владимир, привет. Ну пустые нас не страшат, а всяка ошибочная нечесть это не ко мне :-).

По вопросам из тем форума, личку не читаю.

 

Михаил О.

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

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

Артем Кузнецов

, я чуть подправил код выше, попробуйте его

 

Михаил Витальевич С.

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

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

#16

19.08.2020 14:54:19

Цитата
Артем Кузнецов написал:
ну excel считает запись «2» текстом

вообще то, и IsNumeric(«2»)=True и IsNumeric(2)=True

 

БМВ

Модератор

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

Excel 2013, 2016

Как хорошо что я не Михаил … :-)

По вопросам из тем форума, личку не читаю.

 

Артем Кузнецов

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

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

#18

19.08.2020 15:22:36

Цитата
Михаил Витальевич С. написал:
вообще то, и IsNumeric(«2»)=True и IsNumeric(2)=True…

хм, интересно, на фига тогда делать в excel эту запись «2»  как текст, если сама же excel’евская функция numeric воспринимает её как число, но с другой стороны так даже лучше, наверное …..    

Изменено: Артем Кузнецов19.08.2020 15:22:55

 

sokol92

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

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

Вы смешиваете Excel и VBA. Каждый живет своей жизнью. Описание IsNumeric

здесь

. Дополнительно учтите, что IsNumeric учитывает региональные настройки.

Изменено: sokol9219.08.2020 15:29:28

 

Артем Кузнецов

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

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

#20

20.08.2020 22:46:32

а так она работает если без call, спасибо, выложу на всякий случай полный код, вдруг кому пригодиться, и кстати обработчик ошибок по другом уне много сделан  

Код
'Находит по строкам в каждой строке максимальное и минимальное значение и выводит результат в 10 столбец
Sub Массив_Макс_Мин()
Dim myArray()
Dim i As Long
Dim j As Long
Dim max As Long
Dim min As Long
Dim myCell As Range

On Error Resume Next            'что бы не вылетала ошибка при нажатии на Esc или Отмена
ErrorHandle:
      Set myCell = Application.InputBox(prompt:="Выделите диапазон", Type:=8)       'выделение ячеек через InputBox

On Error GoTo ErrorHandle
      If myCell.Count = 1 Then
            MsgBox "Выделите диапазон", vbExclamation, "Внимание"    'если выбрана только одна ячейка
            Exit Sub
        End If
         
        Dim Val As Variant
        For Each Val In myCell
            If Not IsNumeric(Val) Then               'если выбраны не числа
                MsgBox "Выделите числа", vbExclamation, "Внимание"
                Exit Sub
            End If
        Next Val
        

      myArray = myCell.Value
      For i = 1 To UBound(myArray, 1)
          max = myArray(i, 1)
          min = myArray(i, 1)
          For j = 1 To UBound(myArray, 2)
              If myArray(i, j) > max Then
                  max = myArray(i, j)
              ElseIf myArray(i, j) < min Then
                  min = myArray(i, j)
              End If
          Next j
          Cells(i, 10).Value = "max" & " " & max & " " & "min" & " " & min
      Next i
      Set myCell = Nothing        'освобождение памяти, желательно делать для всех Set в конце
End Sub

Изменено: Артем Кузнецов10.09.2020 02:07:53

 

Михаил О.

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

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

#21

20.08.2020 22:49:45

Ну, видите, общими усилиями справились

Я не Михаил…

In VBA, to test whether an expression is a number, the IsNumeric function can be used.

Description

The IsNumeric function evaluates whether the input expression is a number and returns a Boolean value (TRUE or FALSE). It returns True if the entire expression is a number; otherwise, it returns False.

Syntax

IsNumeric(expression)

The input expression is either a numeric expression or a string expression.

VBA examples of IsNumeric

Example 1 – Using IsNumeric with IF-THEN-ELSE

The following VBA function CheckNumeic uses IsNumeric to test whether input1 is numeric or not with an IF-THEN-ELSE statement.

Function CheckNumeric(ByVal input1) As String
If IsNumeric(input1) = True Then
    MyFunction1 = "Input is numeric"
Else
    MyFunction1 = "Input is not numeric"
End If
End Function

I would want to draw your attention to line 2. While this line is correct, it is not necessary. Instead, it can be written as:

If IsNumeric(input1) Then

In VBA, whenever you perform a logical test, for the condition of TRUE, you don’t have to type the =TRUE in the statement.

Example2 – Negate the result of IsNumeric

The VBA function below returns the opposite of IsNumeric. The function uses the same IF-THEN-ELSE structure.

Function IsNumericReverse(ByVal input1) As Boolean
If IsNumeric(input1) = True Then
    IsNumericReverse = False
Else
    IsNumericReverse = True
End If
End Function

However, this entire structure is not necessary. Instead, the function can be simplified as follows. The Not logical operator can be used to reverse (negate) the answer of IsNumeric, which serves the objective of the function in this case.

Function IsNumericReverse(ByVal input1) As Boolean
    IsNumericReverse = Not (IsNumeric(input1))
End Function

Example 3 – VBA action if not numeric

The VBA function counts the number of non-numeric cells in the input range. In line 5, note the use of Not with IsNumeric. In the sentence structure here, putting a space after Not is enough, which is equivalent to using a bracket after Not to wrap the condition being tested.

Function countNonNumeric(range1 As Range) As Long
Dim cell As Range
Dim counter As Long
For Each cell In range1.Cells
    If Not IsNumeric(cell.Value) Then 'use Not to test for non-numeric
        counter = counter + 1
    End If
Next
countNonNumeric = counter
End Function

 

Special Case with Blank

When using IsNumeric, you need to be aware that “blank” (string of zero length) does not mean zero (0) and it is considered to be non-numeric:

IsNumeric("")  returns False

Therefore, when you write your macro, if you want to treat blank as numeric, you may have to use conditional statements to handle the case of blank string inputs.

Special Case with Dates

Another special case with IsNumeric is the treatment of date inputs. Most people conceptually think dates are numeric (after all, they can be converted into date-serials in the computer). However the IsNumeric function in VBA considers dates as non-Numeric:

IsNumeric("10/2/2020")            returns False

Even if you try to input a date truly in Date format, IsNumeric still returns False:

IsNumeric(DateSerial(2020, 10, 2))              returns False

Therefore, you may also need to use conditional statements to handle the case of dates expressions.

Special Case with Time

Handling of time expressions by the ISNUMERIC is difficult to manage, or I would describe it as unpredictable. Therefore, when you input expressions contain time expressions, you must test your macro thoroughly.

There are three possibilities with time expressions. Let’s experiment with the macro below. In cell A1, we place a time of “3:00:00 AM” first. Then we run the macro which test 3 cases:

  • time in form of string (variable x1)
  • time in form of time value (variable x2)
  • time placed in a cell in an Excel sheet (variable x3)

A cell with the time 3:00am

Sub TimeCases()
Dim y
    x1 = IsNumeric("3:00:00 AM")
    x2 = IsNumeric(TimeSerial(3, 0, 0))
    y = Range("A1").Value
    x3 = IsNumeric(y)
    MsgBox x1 &amp;amp;amp;amp;amp; Chr(10) &amp;amp;amp;amp;amp; x2 &amp;amp;amp;amp;amp; Chr(10) &amp;amp;amp;amp;amp; x3
End Sub

Run the macro and the answers will be displayed in the Msgbox:

msgbox stating False, False, True

Calling Excel Worksheet Function ISNUMBER() in VBA

As an alternative to IsNumeric in VBA, you may call the Excel worksheet function ISNUMBER()  in your macro. There are two ways to do this. See line 2 and line 3 in the VBA function below, which do the same job. (I personally prefer Method 2.)

Function CallIsNumber(input1) As Boolean
x = WorksheetFunction.IsNumber(input1) 'Method 1'
x = Application.IsNumber(input1)		'Method 2'
CallIsNumber = x
End Function

VBA ISNUMERIC vs ISNUMBER Worksheet Function

Although you can either use IsNumeric or Excel worksheet function ISNUMBER to check whether an input expression is numeric, you have to be aware of the differences between the two methods in order to program your macros correctly to produce expected result.

Expression Date type of expression ISNUMERIC returns (VBA) ISNUMBER returns (worksheet function)
123 Number TRUE TRUE
“123” Number in form of string TRUE FALSE
12/2/2020 Date FALSE TRUE
“12/2/2020” Date in form of String FALSE FALSE
DateSerial(2020,10,2) Date in form of Date Value FALSE FALSE
3:00:00 AM Time placed in a cell TRUE TRUE
“3:00:00 AM” Time in form of String FALSE FALSE
TimeSerial(3, 0,0) Time in form of Time Value FALSE FALSE
“” (blank) String FALSE TRUE

See also:

  • Else if in VBA

Return to VBA Code Examples

This tutorial will teach you how to use the IsNumeric and IsNumber functions in VBA to check if values are numbers.

IsNumeric is a built-in VBA function, while IsNumber is an Excel function which can be called from VBA code.

Difference between IsNumber and IsNumeric in VBA

IsNumber checks if a value is stored as a number. Whereas, IsNumeric checks if a value can be converted into a number.

For example, if you pass a blank cell as a parameter, IsNumber will return FALSE, while IsNumeric will return TRUE. Also, if you pass a cell containing number stored as a text, IsNumber will return FALSE and IsNumeric TRUE.

You need to pay attention to these limitations of both functions and decide in which cases is better to use IsNumeric and when IsNumber.

Using IsNumeric in VBA

IsNumeric is the VBA function which checks if a value is numeric and returns a Boolean TRUE or FALSE as a result.

The function can take a variable or a cell value.

Here is an example of taking a cell value:

If IsNumeric(Sheet1.Range("A1").Value) = True Then
    MsgBox "The value in A1 is numeric"
Else
    MsgBox "The value in A1 is not numeric"
End If

In this example, we check if the value from the cell A1 is numeric using the IsNumeric. This function returns the appropriate message, depending on the result of the function.

This next example perform the same operation, except with a variable instead of a cell value:

Dim n as Variant

n = Sheet1.Range("A1").Value

If IsNumeric(n) = True Then
    MsgBox "The value in A1 is numeric"
Else
    MsgBox "The value in A1 is not numeric"
End If

Using IsNumber in VBA

IsNumber is an Excel Function, which can be used in VBA. It has an almost similar output as IsNumeric. Let’s look at the example of the IsNumber function:

If Application.WorksheetFunction.IsNumber(Sheet1.Range("A1").Value) = True Then

    MsgBox "The value in A1 is numeric"

Else

    MsgBox "The value in A1 is not numeric"

End If

As you can see from the code, the difference is in the syntax when calling the function. Since IsNumber is the Excel function, we need to put Application.WorksheetFunction before the function call.

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!

  • #2

It’s:

If Not IsNumeric(ActiveCell.Value) Then

  • #3

Perhaps:

Code:

Sub test()
If Not (IsNumeric(ActiveCell)) And ActiveCell.Column <> 256 Then ActiveCell.Offset(, 1).Select
End Sub

  • #4

Thankyou both HOTPEPPER and Andrew, but I used Andrew’s code as I found it much simpler.

  • #5

Another question now. If I have been moving the active cell about by using offset, if I want to find out where the cell is, how do I do that. Whether it is in A1 form or 1, 1 it doesn’t matter.

Cheers again :)

  • #6

Luapo said:

Another question now. If I have been moving the active cell about by using offset, if I want to find out where the cell is, how do I do that. Whether it is in A1 form or 1, 1 it doesn’t matter.

Cheers again :)

Like this?

MsgBox ActiveCell.Address

  • #7

yeah that is great, now is there a way to separate the row number so I can use it as a variable?

  • #8

Question is, why are you moving the activecell about using offset.. To what purpose? Is there an underlying issue we need to address here?

  • #9

Luapo said:

yeah that is great, now is there a way to separate the row number so I can use it as a variable?

Like this:

MsgBox ActiveCell.Row

  • #10

Or, let’s say you actually declare your variables …

Code:

Dim myVar as Long
'... other code ...
myVar = Activecell.Row

I’m still rather curious as to what you’re trying to do..

Понравилась статья? Поделить с друзьями:
  • Vba excel if not is nothing then
  • Vba excel if not exists
  • Vba excel if not exist
  • Vba excel if label userform
  • Vba excel if isna