If excel vba or and одновременно

I want redistribute an Excel file with 14 Columns to the correct Column (with 12.000 rows).

For this I have to use some If And Or Statements to put the numbers in a matrix. But apparently I don’t get the right things out of it.

It makes all my cells zero, while the cells with a value should keep the value.

Where do I go wrong?:

    For i = 1 To LastRow
    If Cells(i, 8).Value2 = "" Then Cells(i, 8).Value2 = 0

    If Cells(i, 1).Value2 < 437 And Cells(i, 5).Value2 = "aa" _
    Or Cells(i, 5).Value2 = "bb" _
    Or Cells(i, 5).Value2 = "cc" _
    Or Cells(i, 5).Value2 = "dd" _
    Or Cells(i, 5).Value2 = "ee" _
    Or Cells(i, 5).Value2 = "ff" _
    Or Cells(i, 5).Value2 = "gg" _
    And Cells(i, 7).Value2 = "" _
    Then Cells(i, 7).Value2 = 0

    Next i

So if the cell contains an aa or bb or cc or dd or ee or ff or gg and is empthy the cell should become 0 otherwise it should stay the same value. After that it should go into a matrix

Then Matrixgetallen(i, 2) = CDbl(Cells(i, 7).Value2)

But I didn’t manage to get that in the same if statement.

If have 6 of these kind of If-statements, so probably If Then Else doesn’t work.

Содержание

  1. VBA If – And, Or, Not
  2. IF…AND
  3. IF NOT…
  4. VBA Code Examples Add-in
  5. VBA IF OR
  6. IF OR Function in VBA
  7. How to Use IF with OR Function in VBA?
  8. IF OR VBA Function with Loops (Advanced)
  9. Recommended Articles
  10. VBA IF OR (Test Multiple Conditions)
  11. Use OR with IF
  12. Multiple Conditions with IF OR
  13. «And» and «Or» troubles within an IF statement
  14. 3 Answers 3
  15. Update:

VBA If – And, Or, Not

In this Article

This article will demonstrate how to use the VBA If statement with And, Or and Not.

When we us an IF statement in Excel VBA, the statement will execute a line of code if the condition you are testing is true.

  • We can use AND statement and OR statements in conjunction with IF statements to test for more than one condition and direct the code accordingly.
  • We can also use a NOT statement with an IF statement to check if the condition is NOT true – it basically is the inverse of the IF statement when used alone.

IF…AND

We can use the IF…AND combination of logical operators when we wish to test for more than one condition where all the conditions need to be true for the next line of code to execute.

For example, consider the following sheet:

To check if the Profit is over $5,000, we can run the following macro:

This macro will check that the cell C5 is greater or equal to $10,000 AND check that the cell B6 is less than $5,000. If these conditions are BOTH true, it will show the message box.

If we amend the macro to check if C5 is just greater than $10,000, then the profit would not be achieved!

We can use the IF…OR combination of logical operators when we wish to test for more than one condition where only one of the conditions needs to be true for the next line of code to execute.

The format for this is almost identical to the IF…AND example above.

However, with this macro, because we are using an IF …OR statement, only one of the conditions needs to be true.

IF NOT…

IF..NOT changes the IF statement around – it will check to see if the condition is NOT true rather than checking to see if the condition is true.

In this example above, the IF statement is checking to see if the value in C5 is NOT smaller than 10000.

Therefore this line of code:

and this this line of code:

are testing for the same thing!

VBA Code Examples Add-in

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

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

Источник

VBA IF OR

IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.

IF OR Function in VBA

Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)

How to Use IF with OR Function in VBA?

We will show you a simple example of using the IF OR function in VBA.

A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.

Now, look at the syntax of the IF OR function in VBA.

It is the same as we saw in the worksheet example. For a better understanding, look at the below example.

We have the previous month’s price, the last 6-month average price, and the current monthly price here.

To decide whether to buy the product, we need to do some tests here, and those tests are.

If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”

Step 1: Open the IF condition inside the Sub procedure.

Code:

Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value

Step 3: The first logical condition completes. Now, open OR statement.

Code:

Step 4: Now, apply the second logical condition as Range(“D2”).Value

Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”

Code:

Step 6: In the next line, write what the result should be if the logical test Logical Test A logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test. read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.

Code:

Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.

Code:

Step 8: Close the IF statement with “End If.”

Code:

We complete the coding part.

Let us run this code using F5 or manually through the run option and see the result in cell E2.

We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.

IF OR VBA Function with Loops (Advanced)

Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loops Use VBA Loops A VBA loop in excel is an instruction to run a code or repeat an action multiple times. read more .

We have added a few more lines for the above data set.

We need to use the For Next Loop here.

Just keep the current code as it is.

Declare the variable as an Integer.

Now, open For Next Loop from 2 to 9.

For example, Range (“D2”).Value should be Range (“D” & k).Value

Now, run the code. First, we should get the status in all the cells.

You can copy the code below.

Code:

Recommended Articles

This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –

Источник

VBA IF OR (Test Multiple Conditions)

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Use OR with IF

  1. First, start the IF statement with the “IF” keyword.
  2. After that, specify the first condition that you want to test.
  3. Next, use the OR keyword to specify the second condition.
  4. In the end, specify the second condition that you want to test.

To have a better understanding let’s see an example.

If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2

Now let’s see if both conditions are false, let me use a different code here.

In the above code, both conditions are false, and when you run this code, it executes the line of code that we have specified if the result is false.

Multiple Conditions with IF OR

In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.

Now we have three conditions to test, and we have used the OR after the second condition to specify the third condition. As you learned above that when you use OR, any of the conditions need to be true to get true in the result. When you run this code, it executes the line of code that we have specified for the true.

And if all the conditions are false, just like you have in the following code, it returns false.

Источник

«And» and «Or» troubles within an IF statement

I’m trying to use «And» & «Or» within an If statement. I probably have my syntax wrong.

the result comes back false when the data should make it true. Here is the code:

-When I debug and come to this line it hops over it and doesn’t enter in.

-origNum actually equals «006260006» and creditOrDebit = «D».

-so I’m assuming my «Or» statement isn’t working.

-Hopefully this is a quick easy question. Thanks!

3 Answers 3

The problem is probably somewhere else. Try this code for example:

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

This is not an answer, but too long for a comment.

In reply to JP’s answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class — but in summary, it uses a kernel32 function which is fairly accurate ( Private Declare Sub GetLocalTime Lib «kernel32» (lpSystemTime As SYSTEMTIME) ).

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 — Last Run: 156 — Average Run: 156
or_and (x1): 125 — Last Run: 125 — Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 — Last Run: 156 — Average Run: 156
or_and (x1): 125 — Last Run: 125 — Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 — Last Run: 140 — Average Run: 140
or_and (x1): 125 — Last Run: 125 — Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 — Last Run: 140 — Average Run: 140
or_and (x1): 141 — Last Run: 141 — Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 — Last Run: 156 — Average Run: 156
or_and (x1): 125 — Last Run: 125 — Average Run: 125

Note

If creditOrDebit is not «D» , JP’s code runs faster (around 60ms vs. 125ms for the or/and code).

I like assylias’ answer, however I would refactor it as follows:

This might save you some CPU cycles since if creditOrDebit is <> «D» there is no point in checking the value of origNum .

Update:

I used the following procedure to test my theory that my procedure is faster:

I must have a slow computer because 1,000,000 iterations took nowhere near

200 ms as with assylias’ test. I had to limit the iterations to 10,000 — hey, I have other things to do 🙂

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>«D» , my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it — to short-circuit the logic so that origNum doesn’t need to be evaluated when creditOrDebit <> «D» .

At this point, the rest depends on the OP’s spreadsheet. If creditOrDebit is likely to equal D, then use assylias’ procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

Источник

Home / VBA / VBA IF OR (Test Multiple Conditions)

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Use OR with IF

  1. First, start the IF statement with the “IF” keyword.
  2. After that, specify the first condition that you want to test.
  3. Next, use the OR keyword to specify the second condition.
  4. In the end, specify the second condition that you want to test.

To have a better understanding let’s see an example.

Sub myMacro()

'two conditions to test using OR
If 1 = 1 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None of the conditions are true."
End If

End Sub

If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 < 1), and here only the first condition is true, and even though it has executed the line of code that we have specified if the result is true.

Now let’s see if both conditions are false, let me use a different code here.

Sub myMacro()

'two conditions to test using OR
If 1 = 2 Or 2 < 1 Then
    MsgBox "One of the conditions is true."
Else
    MsgBox "None of the conditions are true."
End If

End Sub

In the above code, both conditions are false, and when you run this code, it executes the line of code that we have specified if the result is false.

In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.

Sub myMacro()

'three conditions to test using OR

If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
    MsgBox "one of the conditions is true."
Else
    MsgBox "none of the conditions are true."
End If

End Sub

Now we have three conditions to test, and we have used the OR after the second condition to specify the third condition. As you learned above that when you use OR, any of the conditions need to be true to get true in the result. When you run this code, it executes the line of code that we have specified for the true.

And if all the conditions are false, just like you have in the following code, it returns false.

Sub myMacro()

'three conditions to test using OR
If 1 < 1 And 2 < 1 And 1 + 1 = 0 Then

    MsgBox "one of the conditions is true."

Else

    MsgBox "none of the conditions are true."

End If

End Sub

deka6pb21

1 / 1 / 0

Регистрация: 04.03.2013

Сообщений: 42

1

10.03.2013, 13:18. Показов 21058. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Ребята посмотрите пожалуйста где ошибка, вместо того чтобы удалять ячейки в которых нет 00 или 03 или 06 и т.д.
Удаляется все.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Sub aero2()
    Dim wsh As Worksheet
    Dim i As Long
    Dim j As Long
    Dim m As Long
 
Set wsh = ActiveWorkbook.ActiveSheet
 
    
    
    
    For m = wsh.UsedRange.Row + wsh.UsedRange.Rows.Count - 1 To 1 Step -1
        If wsh.Rows(m).Text = "" Then Else Exit For
    Next
    
    i = 1 ' Первая строка данных ддля обработки
    j = 1 ' Используется для автонумерации
    Do While i <= m ' Цикл обхода всех строк
 If (Range("D" & i).Text <> "00") Or (Range("D" & i).Text <> "03") Or (Range("D" & i).Text <> "06") Or (Range("D" & i).Text <> "09") Or (Range("D" & i).Text <> "12") Or (Range("D" & i).Text <> "15") Or (Range("D" & i).Text <> "18") Or (Range("D" & i).Text <> "21") Then
        Rows(i & ":" & i).Select
        Selection.ClearContents
        End If
        i = i + 1
    Loop
    
End Sub

Добавлено через 9 минут
Или может вообще это можно как-то полегче сделать средствами встроенных функций excel?
Через сортировку там.
Буду благодарен если научите



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

10.03.2013, 13:18

Ответы с готовыми решениями:

Отметить полужирным шрифтом в исходном тексте слова имеющие приставки «пре», «при», «на», «не»
Отметить полужирным шрифтом в исходном тексте слова имеющие приставки &quot;пре&quot;,
&quot;при&quot;, &quot;на&quot;, &quot;не&quot;….

Проверить, содержит ли строка символы отличные от «+», «-«, «*» и «/»
&quot;+&quot;, &quot;-&quot;, &quot;*&quot; и &quot;/&quot;

вот

начал, дальше не знаю что делать

Sub rr()

Dim s As String,…

MS Acces VBA. Как вывести поле «фамилия» и «группа» из таблицы «студенты» в Access ?
Использовать Fields? Посмотрите в рисунке задания.

Выборка уникальных дат из строк листа «l1» и помещение их в лист «l3», Не получается. На листе «l3» вставляет
Запускаю с листа &quot;l1&quot; построчно работает, но мне нужно, чтобы заполнялись столбцы, начиная со…

5

Watcher_1

356 / 162 / 27

Регистрация: 21.06.2011

Сообщений: 350

10.03.2013, 13:37

2

Замените

Visual Basic
1
 If (Range("D" & i).Text <> "00") Or (Range("D" & i).Text <> "03") Or (Range("D" & i).Text <> "06") Or (Range("D" & i).Text <> "09") Or (Range("D" & i).Text <> "12") Or (Range("D" & i).Text <> "15") Or (Range("D" & i).Text <> "18") Or (Range("D" & i).Text <> "21") Then

на

Visual Basic
1
 If Range("D" & i).Text <> "00" And Range("D" & i).Text <> "03" And Range("D" & i).Text <> "06" And Range("D" & i).Text <> "09" And Range("D" & i).Text <> "12" And Range("D" & i).Text <> "15" And Range("D" & i).Text <> "18" And Range("D" & i).Text <> "21" Then



2



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

10.03.2013, 13:48

3

Чтобы строка влезала в монитор , замените If…End If на

Visual Basic
1
2
3
4
 Select Case Range("D" & i).Text
 Case "00", "03", "06", "09", "12", "15", "18", "21"
 Case Else: Rows(i).ClearContents
 End Select



2



Igor_Tr

4377 / 661 / 36

Регистрация: 17.01.2010

Сообщений: 2,134

10.03.2013, 13:48

4

Попробуйте так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Sub aero2()
    Dim wsh As Worksheet
    Dim i As Long
    Dim j As Long
    Dim m As Long
 
    Set wsh = ActiveWorkbook.ActiveSheet
    
    If wsh.Rows(m).Text = "" Then Exit For
    
    i = 1 ' Первая строка данных ддля обработки
    j = 1 ' Используется для автонумерации
    for i = m to 1 Step -1 
       If (Range("D" & i).Text <> "00") Or _
           (Range("D" & i).Text <> "03") Or _
              (Range("D" & i).Text <> "06") Or _
                 (Range("D" & i).Text <> "09") Or _
                     (Range("D" & i).Text <> "12") Or 
                        (Range("D" & i).Text <> "15") Or _
                            (Range("D" & i).Text <> "18") Or _
                               (Range("D" & i).Text <> "21") Then
           Rows(i).delete
        End If
    next 'i
End Sub

Но у «Казанский» лучьше! Здесь только для показа If…. end if



1



3217 / 966 / 223

Регистрация: 29.05.2010

Сообщений: 2,085

10.03.2013, 14:49

5

Igor_Tr, а в строке №9 зачем Exit For, или описка?



0



4377 / 661 / 36

Регистрация: 17.01.2010

Сообщений: 2,134

10.03.2013, 15:09

6

Это строка оригинала, не моя. Очень не присматривался. и корректировал прямо в окне. Она целая там не нужна вобще!!!!

Добавлено через 11 минут
Но если очень хочется, тогда

If wsh.Rows(m).Text = «» Then Exit Sub

Если значения в последней значения нет, тогда выйти. А зачем тогда заходить?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

10.03.2013, 15:09

Помогаю со студенческими работами здесь

Присвоить значение «10» элементам большим «120» и меньшим»150″ масива Р(10,20)
Простите за дублирование, но мой прошлый вопрос не увенчался большим успехом…
Присвоить значение…

Как сделать, чтобы kod= «=Find(«»,»», R2C1, 1)»
Как следующий код

Cells(1, 9).Select
ActiveCell.FormulaR1C1 = ‘=Find(»,», R2C1, 1)’
kod =…

В последнем абзаце удалить все вхождения символов «+»,»-«, «*»
Дан любой текст
В последнем абзаце удалить все вхождения символов &quot;+&quot;,&quot;-&quot;, &quot;*&quot;.

Нужно что бы при установки галки сумма вбитая в кол-ку «сумма» переходила в «Частично оплаченно» далее в «остаток»
Помогите умоляю. От этого зависет моя дальнейшая трудовая деятельность.Итак к главному.Смысл вот в…

Как задать диапазон Shapes. Range(Array(«Text box 1», «Text box 2», «Text box 3», «Text box 4».»Text box 10″).Select
Здравствуйте, все. Подскажите, пожалуйста, возможно ли в макросе VBA MS Word заменить область…

Маленькое продолжение темы «Аналог Excel-метода «OnTime»» или про многопоточность
Коллеги, хочу добавить несколько слов … (раз уж речь зашла про 2003 офис)
Комментарий: на счет…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

Return to VBA Code Examples

In this Article

  • IF…AND
  • IF…OR
  • IF NOT…

This article will demonstrate how to use the VBA If statement with And, Or and  Not.

When we us an IF statement in Excel VBA, the statement will execute a line of code if the condition you are testing is true.

  • We can use AND statement and OR statements in conjunction with IF statements to test for more than one condition and direct the code accordingly.
  • We can also use a NOT statement with an IF statement to check if the condition is NOT true – it basically is the inverse of the IF statement when used alone.

IF…AND

We can use the IF…AND combination of logical operators when we wish to test for more than one condition where all the conditions need to be true for the next line of code to execute.

For example, consider the following sheet:

vba if and

To check if the Profit is over $5,000, we can run the following macro:

Sub CheckProfit()
   If Range("C5") >= 10000 And Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

This macro will check that the cell C5 is greater or equal to $10,000 AND check that the cell B6 is less than $5,000. If these conditions are BOTH true, it will show the message box.

vba if and msg

If we amend the macro to check if C5 is just greater than $10,000, then the profit would not be achieved!

vba if and else

IF…OR

We can use the IF…OR combination of logical operators when we wish to test for more than one condition where only one of the conditions needs to be true for the next line of code to execute.

The format for this is almost identical to the IF…AND example above.

Sub CheckProfit()
   If Range("C5") > 10000 Or Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

However, with this macro, because we are using an IF …OR statement, only one of the conditions needs to be true.

vba if or

IF NOT…

IF..NOT  changes the IF statement around – it will check to see if the condition is NOT true rather than checking to see if the condition is true.

Sub CheckProfit() 
If NOT Range("C5")< 10000 Or Range("C6") < 5000 Then 
   MsgBox "$5,000 profit achieved!" 
Else 
   Msgbox "Profit not achieved!" 
End If 
End Sub

In this example above, the IF statement is checking to see if the value in C5 is NOT smaller than 10000.

Therefore this line of code:

IF Range("C5") > 10000

and this this line of code:

IF NOT Range("C5") < 10000

are testing for the same thing!

Понравилась статья? Поделить с друзьями:
  • If error vba excel 2007
  • Idioms with word black
  • If error null excel
  • Idioms with word beat
  • If error excel 2010