Separate Even, Odd and Equal values in Matrix by VBA (Excel)

Asked

Viewed 1,216 times

3

how to make a 10x10 matrix, separate pairs and odd and equal without using Mod ?inserir a descrição da imagem aqui

1 answer

2


NOW WITH CODE READY AND TESTED!

To solution presented in the code below treats each element of the matrix at a time to identify the numbers pairs and odd contained in it. In the sequence, within the order of analysis per element of the matrix, there is also the verification of how many values are equal (considering the total amount that each repeated number is in the matrix) and how many numbers are Repeated (if you want to distinguish "equal" from "repeated" as I did, otherwise your "equal" is my "repeated"):

Option Explicit

Private Sub UserForm_Initialize()

    SepararValores

End Sub

Private Sub SepararValores()

    Dim Matriz(10, 10), Pares(100), Impares(100), Iguais(100) As String

    Dim Qtde_Pares, Qtde_Impares, Qtde_Iguais, _
        MenorNumeroInteiro, MaiorNumeroInteiro, _
        NumeroDeLinhas, NumeroDeColunas, _
        i, j, s, t, k, Aux_IndiceIguais As Integer

    Dim Aux_String, Linha As String

    Dim OcorrenciaDeNumerosIguais As Boolean

    Aux_String = ""

    NumeroDeLinhas = 10 'A matriz está dimensionada para ser no máximo 10 x 10, mas pode alterar o dimensionamento se precisar.
    NumeroDeColunas = 10

    MenorNumeroInteiro = 1
    MaiorNumeroInteiro = 99

    Aux_String = " Matriz " & NumeroDeLinhas & " x " & NumeroDeColunas

    Debug.Print ""
    Debug.Print Aux_String
    Debug.Print " " & Left("--------------------", Len(Aux_String) - 1)
    Debug.Print ""

    Linha = ""

    Randomize

    'Preenche a matriz
    For i = 1 To NumeroDeLinhas

        For j = 1 To NumeroDeColunas

            Matriz(i, j) = CStr(Int((MaiorNumeroInteiro - MenorNumeroInteiro + 1) * Rnd()) + MenorNumeroInteiro)

            If Len(CStr(Matriz(i, j))) < 2 Then Matriz(i, j) = "0" & Matriz(i, j)

            Linha = Linha & " " & Matriz(i, j)

        Next j

        Debug.Print Linha

        Debug.Print ""

        Linha = ""

    Next i

    Debug.Print ""
    Debug.Print " Solução"
    Debug.Print " -------"
    Debug.Print ""

    Qtde_Pares = 0
    Qtde_Impares = 0
    Qtde_Iguais = 0

    Aux_IndiceIguais = 0 'Indice para registro dos números Iguais

    'Trata cada elemento da matriz por vez, para achar os
    'Pares, Ímpares e os Iguais
    For i = 1 To NumeroDeLinhas

        For j = 1 To NumeroDeColunas

            If Int(Matriz(i, j) / 2) - Matriz(i, j) / 2 = 0 Then
              'Se é Par

               Qtde_Pares = Qtde_Pares + 1

               Pares(Qtde_Pares) = Matriz(i, j)

            Else
              'Se é Ímpar

               Qtde_Impares = Qtde_Impares + 1

               Impares(Qtde_Impares) = Matriz(i, j)

            End If

            'Calcula a quantidade de valores iguais na matriz
            'Sem refazer para um mesmo valor

            OcorrenciaDeNumerosIguais = False

            For s = 1 To NumeroDeLinhas

                For t = 1 To NumeroDeColunas

                    'Faz se encontrou um valor igual, mas que
                    '"i" e "j" não sejam iguais a "s" e "t" simultaneamente
                    If Matriz(s, t) = Matriz(i, j) And (s <> i Or t <> j) Then

                        'Faz se é um valor não encontrado anteriormente
                        If s > i Or (s = i And t > j) Then

                            Qtde_Iguais = Qtde_Iguais + 1

                            If Not OcorrenciaDeNumerosIguais Then

                                OcorrenciaDeNumerosIguais = True

                                Qtde_Iguais = Qtde_Iguais + 1
                                'Soma mais um pois deve considerar o
                                'próprio número procurado

                                'Fica com a quantidade de números repetidos
                                Aux_IndiceIguais = Aux_IndiceIguais + 1

                                Iguais(Aux_IndiceIguais) = Matriz(i, j)

                            End If

                        Else

                           'Se é um valor já considerado anteriormente,
                           'deve ignorá-lo e já passar a pegar o próximo,
                           'senão duplicaria várias vezes este resultado,
                           'pois já pegou todos da primeira vez

                           GoTo Sair_deste_loop

                        End If

                    End If

                Next t

            Next s

        Sair_deste_loop:

        Next j

    Next i

    'Parte da impressão de daodos
    'Use a Janela de Verificação Imediata do VBA
    'Para ver a matriz e os respectivos resultados

    Linha = ""

    For i = 1 To Qtde_Pares

        Linha = Linha & " " & Pares(i)

    Next i

    Debug.Print " " & Qtde_Pares & " números Pares:" & Linha
    Debug.Print ""

    Linha = ""

    For i = 1 To Qtde_Impares

        Linha = Linha & " " & Impares(i)

    Next i

    Debug.Print " " & Qtde_Impares & " números Ímpares:" & Linha
    Debug.Print ""

    Linha = ""

    For i = 1 To Aux_IndiceIguais

        Linha = Linha & " " & Iguais(i)

    Next i

    Debug.Print " " & Qtde_Iguais & " números Iguais:" & Linha
    Debug.Print ""
    Debug.Print " " & Aux_IndiceIguais & " números Repetidos."
    Debug.Print ""

    Beep

End Sub
  • 1

    Luana, READY! Here is the code COMPLETE and TESTED!

  • Leo, unfortunately I can’t do it, but thank you so much for your help :)

  • 1

    Hi Luana, as I did just copy and paste in the code part of a new form, open the VBA Immediate Verification Window and run, the form will appear with nothing (no objects), but in the check window is shown the matrix and all solutions. Do this which is very cool, if you have difficulty tell me which ones to help you. Then, please mark the answer. Be sure to try, we are all here in the community to learn and share knowledge.

  • 1

    So it worked out now, thank you very much :)

  • Thanks! Good studies.

  • I have a question in case for form looks in excel spreadsheet had to if another code using Cells ?

  • Hi Luana, I didn’t understand your question, but if you want to put the results in the spreadsheet, you can use Cells(row, column) = Value, or Range("B3"). Value = Value, or if the cell has a name: Range("Name"). Value = Value. Have you got the schema from here? You can also vote if you did not vote (arrows), and if you have more doubts the ideal is to create another question showing part of your code where you are having difficulty and describe its difficulty, because it is bad to extend the conversations here by the comments, they do not help other interested.

  • Leo, nothing against you having done all the work for AP (your option). But, why did you use UserForm? Sometimes she just wanted a function to use on the spreadsheet. I think you have been studying creating forms in Excel, and so you are using it in everything that is place even without being necessary, no? Beware, otherwise you run the risk of becoming the proverbial example ("For those who only know how to use a hammer, every problem is a nail.") :)

  • Hi Luiz, ok, but I don’t think you noticed that she was doing this in a module!!! If you look at her history, she posted the same question three times (I flagged it as duplicates, see how the moderator indicated it in the comments and not in the titles). As I realized that she was failing to do it, I helped in a sophisticated way, I know... That’s it friend, what I am programming in VBA is nothing "usual", so I need support in the issues I have done, and I thank you very much for the support you have given me, what I am doing is getting very good, soon I will present the project to third.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.