This is my first question here and I must admit, I was not able to find any solution so far here or elsewhere. Here is the problem:
I wanted to program a code, which is supposed to do the following:
- Ask the user how many rows are needed
- Ask, how many columns are needed
- Create a matrix, where in the first column all rows are numbered, in the first row all columns are numbered and within the matrix, all these numbers are the multiplied (row 3/column 4 contains 12, for example).
- Finally, all prime numbers shall be colored.
My problem starts with the last step (in my code beginning at "'Primzahlen hervorheben"). For each combination of row and column I use two for
loops, in which I first assume, the product IS a prime number by setting primzahl = true
and set k = 2
, which is 1 upped through all numbers up to the product itself... BUT for some reason, k
keeps growing and eventually reaches the five digits area, before it crashes. I guess, the problem must be in this line:
Do While (primzahl = True) Or (k <= i * j) Or (i * j <> 1)
I connected all conditions as one would in an if
construct. The Editor itself does not seem to have a problem with this, but why does it ignore the second condition, which does not allow for k
to become larger than i * j
? Am I missing something?
Just to put it in words: The loop shall continue, as long as
- it being not a prime number proves to be the case (p
rimzahl = false
), OR
k
is smaller or equal to i * j
, OR
i * j
is not 1
This case is no emergency or anything, I just want to know, where the hook is. I would appreciate your support and hope, to get some helpful advise.
Sub rechnen()
'Zellen leeren
Cells.ClearContents
Cells.ClearFormats
'Variablen definieren
Dim i As Integer, j As Integer, k As Integer, iMax As Integer, jMax As Integer, primzahl As Boolean
'Variablen Werte zuweisen
iMax = 3 'InputBox("Anzahl Zeilen")
jMax = 5 'InputBox("Anzahl Spalten")
'Eigentliche Prozedur
For i = 1 To iMax
Cells(1 + i, 1).Value = i
For j = 1 To jMax
Cells(1, 1 + j).Value = j
Cells(1 + i, 1 + j).Value = i * j
Next j
Next i
'Spaltenbreite anpassen
ActiveSheet.UsedRange.Columns.AutoFit
'Primzahlen hervorheben
For i = 1 To iMax
For j = 1 To jMax
k = 2
primzahl = True
''''''''
Do While (primzahl = True) Or (k <= i * j) Or (i * j <> 1)
If Cells(1 + i, 1 + j).Value Mod k = 0 Then
primzahl = False
Exit Do
End If
k = k + 1
Loop
''''''''
If primzahl = True Then
Cells(1 + i, 1 + j).Interior.Color = vbRed
End If
Next j
Next i
End Sub
``