Notifications
Clear all

VBA Determinar Range até ultima linha ativa

12 Posts
2 Usuários
0 Reactions
2,019 Visualizações
(@ericksant)
Posts: 0
New Member
Topic starter
 

Prezados,
boa tarde,

Tenho o seguinte código

Option Explicit

Sub export_in_json_format()

    Dim fs As Object
    Dim jsonfile
    Dim rangetoexport As Range
    Dim rowcounter As Long
    Dim columncounter As Long
    Dim linedata As String
    
    ' change range here
    Set rangetoexport = Sheet1.Range("a1:d8")     'Nessa linha, precisava de alguma maneira determinar as colunas "E";"G";"H";"L";"N";"O";P" como range, que irão entrar no código, porém se eu apenas determinar essas colunas, o código vai ler até a última linha da coluna, ou seja, vai ler até a última linha do excel, eu precisava que pegasse até a última linha de cada coluna dessas que possua conteúdo.


    Set fs = CreateObject("Scripting.FileSystemObject")
    ' change dir here
    
    Set jsonfile = fs.CreateTextFile("C:UsersxxDesktop" & "jsondata.json", True)
    
    linedata = "{""Output"": ["
    jsonfile.WriteLine linedata
    For rowcounter = 2 To rangetoexport.Rows.Count
        linedata = ""
        For columncounter = 1 To rangetoexport.Columns.Count
            linedata = linedata & """" & rangetoexport.Cells(1, columncounter) & """" & ":" & """" & rangetoexport.Cells(rowcounter, columncounter) & """" & ","
        Next
        linedata = Left(linedata, Len(linedata) - 1)
        If rowcounter = rangetoexport.Rows.Count Then
            linedata = "{" & linedata & "}"
        Else
            linedata = "{" & linedata & "},"
        End If
        
        jsonfile.WriteLine linedata
    Next
    linedata = "]}"
    jsonfile.WriteLine linedata
    jsonfile.Close
    
    Set fs = Nothing
    
    
End Sub

Até tentei criar um código que identificasse cada 'ultima linha' de cada coluna mas na hora de botar ele no RANGE, não consegui...

Veja:

    Dim UltimaLinhaAtivaE As Long
    Dim UltimaLinhaAtivaG As Long
    Dim UltimaLinhaAtivaH As Long
    Dim UltimaLinhaAtivaL As Long
    Dim UltimaLinhaAtivaN As Long
    Dim UltimaLinhaAtivaO As Long
    Dim UltimaLinhaAtivaP As Long
    
    
    
    UltimaLinhaAtivaE = Planilha1.Cells(Planilha1.Rows.Count, 5).End(xlUp).Row
    UltimaLinhaAtivaG = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaH = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaL = Planilha1.Cells(Planilha1.Rows.Count, 12).End(xlUp).Row
    UltimaLinhaAtivaN = Planilha1.Cells(Planilha1.Rows.Count, 14).End(xlUp).Row
    UltimaLinhaAtivaO = Planilha1.Cells(Planilha1.Rows.Count, 15).End(xlUp).Row
    UltimaLinhaAtivaP = Planilha1.Cells(Planilha1.Rows.Count, 16).End(xlUp).Row

Determinando as ultimias linhas de cada coluna, não sei como colocaria elas no range, exemplo:
' change range here
Set rangetoexport = Sheet1.Range("E1:E&UltimaLinhaAtivaE", "G1:G&UltimaLinhaAtivaG") e por ai vai... ?

Tentei isso mas n consegui...

 
Postado : 30/05/2018 9:58 am
(@xlarruda)
Posts: 0
New Member
 

verifique se essa nomencaltura condiz com sua pasta de trabalho:

Planilha1.Cells..

ou se é Plan1, ou Sheet1..

 
Postado : 30/05/2018 10:52 am
(@ericksant)
Posts: 0
New Member
Topic starter
 

Cara, to fazendo alguns testes aqui e to chegando perto do que eu quero...

Veja o código

Sub export_in_json_format()

    Dim fs As Object
    Dim jsonfile
    Dim rangetoexport As Range
    Dim rowcounter As Long
    Dim columncounter As Long
    Dim linedata As String
    Dim UltimaLinhaAtivaE As Long
    Dim UltimaLinhaAtivaG As Long
    Dim UltimaLinhaAtivaH As Long
    Dim UltimaLinhaAtivaL As Long
    Dim UltimaLinhaAtivaN As Long
    Dim UltimaLinhaAtivaO As Long
    Dim UltimaLinhaAtivaP As Long
    
    
    
    UltimaLinhaAtivaE = Planilha1.Cells(Planilha1.Rows.Count, 5).End(xlUp).Row
    UltimaLinhaAtivaG = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaH = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaL = Planilha1.Cells(Planilha1.Rows.Count, 12).End(xlUp).Row
    UltimaLinhaAtivaN = Planilha1.Cells(Planilha1.Rows.Count, 14).End(xlUp).Row
    UltimaLinhaAtivaO = Planilha1.Cells(Planilha1.Rows.Count, 15).End(xlUp).Row
    UltimaLinhaAtivaP = Planilha1.Cells(Planilha1.Rows.Count, 16).End(xlUp).Row
    
     
    ' range 
    Set rangetoexport = Worksheets("Sheet1").Range("N1:N" & UltimaLinhaAtivaN, "E1:E" & UltimaLinhaAtivaE)    'AQUI se eu configurar até 2 colunas( N e E) ele passa tranquilo e faz exatamente o que eu quero... Porém se eu colocar na ordem que eu quero, ele da erro...


'a ordem das colunas que eu quero colocar é N, O, P, H, G, L, E
'no caso seguiria a mesma lógica
'exemplo
'Set rangetoexport = Worksheets("Sheet1").Range("N1:N" & UltimaLinhaAtivaN, "O1:O" & UltimaLinhaAtivaO, "P1:P" & UltimaLinhaAtivaP, "H1:H" & UltimaLinhaAtivaH, "G1:G" & UltimaLinhaAtivaG, "L1:L" & UltimaLinhaAtivaL, "E1:E" & UltimaLinhaAtivaE)

O erro não está na questão que você perguntou... Porque caso eu coloque apenas 2 colunas, ele faz exatamente o que eu quero...

 
Postado : 30/05/2018 11:01 am
(@xlarruda)
Posts: 0
New Member
 

vai ter de setar cada range e usar o método Union

Ex.

r1 as Range
r2 as Range

.....

set r1 = Worksheets("Sheet1").Range("N1:N" & UltimaLinhaAtivaN)
set r2 = Worksheets("Sheet1").Range("O1:O" & UltimaLinhaAtivaO)

e aí por diante...

depois

rangetoexport = Union(r1,r2,.....)

Segue o seu código com a alteração:

Sub export_in_json_format()

    Dim fs As Object
    Dim jsonfile
    Dim rangetoexport As Range
    Dim rowcounter As Long
    Dim columncounter As Long
    Dim linedata As String
    Dim UltimaLinhaAtivaE As Long
    Dim UltimaLinhaAtivaG As Long
    Dim UltimaLinhaAtivaH As Long
    Dim UltimaLinhaAtivaL As Long
    Dim UltimaLinhaAtivaN As Long
    Dim UltimaLinhaAtivaO As Long
    Dim UltimaLinhaAtivaP As Long
    Dim r1, r2, r3, r4, r5, r6, r7 As Range
    
    
    UltimaLinhaAtivaE = Planilha1.Cells(Planilha1.Rows.Count, 5).End(xlUp).Row
    UltimaLinhaAtivaG = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaH = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaL = Planilha1.Cells(Planilha1.Rows.Count, 12).End(xlUp).Row
    UltimaLinhaAtivaN = Planilha1.Cells(Planilha1.Rows.Count, 14).End(xlUp).Row
    UltimaLinhaAtivaO = Planilha1.Cells(Planilha1.Rows.Count, 15).End(xlUp).Row
    UltimaLinhaAtivaP = Planilha1.Cells(Planilha1.Rows.Count, 16).End(xlUp).Row
    
    r1 = Worksheets("Sheet1").Range("E1:E" & UltimaLinhaAtivaE)
    r2 = Worksheets("Sheet1").Range("G1:G" & UltimaLinhaAtivaG)
    r3 = Worksheets("Sheet1").Range("H1:H" & UltimaLinhaAtivaH)
    r4 = Worksheets("Sheet1").Range("L1:L" & UltimaLinhaAtivaL)
    r5 = Worksheets("Sheet1").Range("N1:N" & UltimaLinhaAtivaN)
    r6 = Worksheets("Sheet1").Range("O1:O" & UltimaLinhaAtivaO)
    r7 = Worksheets("Sheet1").Range("P1:P" & UltimaLinhaAtivaP)  
    
    Set rangetoexport = Union(r1, r2, r3, r4, r5, r6, r7)

'sua range está feita, agora continue seu código aqui...

End Sub
 
Postado : 30/05/2018 12:16 pm
(@ericksant)
Posts: 0
New Member
Topic starter
 

Cara, muito obrigado pelo retorno até aqui... Segui sua sugestão, rodou sem erros, porém ele não trás o resultado esperado... Veja o código:

Option Explicit

Sub export_in_json_format()

    Dim fs As Object
    Dim jsonfile
    Dim rangetoexport As Range
    Dim rowcounter As Long
    Dim columncounter As Long
    Dim linedata As String
    Dim UltimaLinhaAtivaE As Long
    Dim UltimaLinhaAtivaG As Long
    Dim UltimaLinhaAtivaH As Long
    Dim UltimaLinhaAtivaL As Long
    Dim UltimaLinhaAtivaN As Long
    Dim UltimaLinhaAtivaO As Long
    Dim UltimaLinhaAtivaP As Long
    Dim r1 As Range
    Dim r2 As Range
    Dim r3 As Range
    Dim r4 As Range
    Dim r5 As Range
    Dim r6 As Range
    Dim r7 As Range
    
    UltimaLinhaAtivaE = Planilha1.Cells(Planilha1.Rows.Count, 5).End(xlUp).Row
    UltimaLinhaAtivaG = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaH = Planilha1.Cells(Planilha1.Rows.Count, 7).End(xlUp).Row
    UltimaLinhaAtivaL = Planilha1.Cells(Planilha1.Rows.Count, 12).End(xlUp).Row
    UltimaLinhaAtivaN = Planilha1.Cells(Planilha1.Rows.Count, 14).End(xlUp).Row
    UltimaLinhaAtivaO = Planilha1.Cells(Planilha1.Rows.Count, 15).End(xlUp).Row
    UltimaLinhaAtivaP = Planilha1.Cells(Planilha1.Rows.Count, 16).End(xlUp).Row
    
    
    Set r1 = Worksheets("Sheet1").Range("N1:N" & UltimaLinhaAtivaN)
    Set r2 = Worksheets("Sheet1").Range("O1:O" & UltimaLinhaAtivaO)
    Set r3 = Worksheets("Sheet1").Range("P1:P" & UltimaLinhaAtivaP)
    Set r4 = Worksheets("Sheet1").Range("H1:H" & UltimaLinhaAtivaH)
    Set r5 = Worksheets("Sheet1").Range("G1:G" & UltimaLinhaAtivaG)
    Set r6 = Worksheets("Sheet1").Range("L1:L" & UltimaLinhaAtivaL)
    Set r7 = Worksheets("Sheet1").Range("E1:E" & UltimaLinhaAtivaE)
    
    
    
    
    
    ' change range here
    Set rangetoexport = Union(r1, r2, r3, r4, r5, r6,r7)

    Set fs = CreateObject("Scripting.FileSystemObject")
    ' change dir here
    
    Set jsonfile = fs.CreateTextFile("C:Userserick.l.santiagoDesktop" & "jsondata.json", True)
    
    linedata = "{""Output"": ["
    jsonfile.WriteLine linedata
    For rowcounter = 2 To rangetoexport.Rows.Count
        linedata = ""
        For columncounter = 1 To rangetoexport.Columns.Count
            linedata = linedata & """" & rangetoexport.Cells(1, columncounter) & """" & ":" & """" & rangetoexport.Cells(rowcounter, columncounter) & """" & ","
        Next
        linedata = Left(linedata, Len(linedata) - 1)
        If rowcounter = rangetoexport.Rows.Count Then
            linedata = "{" & linedata & "}"
        Else
            linedata = "{" & linedata & "},"
        End If
        
        jsonfile.WriteLine linedata
    Next
    linedata = "]}"
    jsonfile.WriteLine linedata
    jsonfile.Close
    
    Set fs = Nothing
    
    
End Sub

ele trás como resultado:

{"Output": [
{"Supplier Number":"20136570","Supplier Number Desc":"fornecedor1","Invoice Number":""},
{"Supplier Number":"40016609","Supplier Number Desc":"fornecedor2","Invoice Number":"000050412000"},
{"Supplier Number":"40018644","Supplier Number Desc":"fornecedor3","Invoice Number":"10006600"},
{"Supplier Number":"40017433","Supplier Number Desc":"fornecedor4","Invoice Number":"00912200"},
{"Supplier Number":"40017966","Supplier Number Desc":"fornecedor5","Invoice Number":"00055900"}
]}

é como ele só considerasse as 3 primeiras ranges, as colunas N, O, P, desconsiderando as H, G, L, E...

Acho que tem algo haver com o formato das células a serem transformadas em json... Consegue identificar isso no código para eu corrigir ?

 
Postado : 30/05/2018 12:46 pm
(@xlarruda)
Posts: 0
New Member
 

Descupe, não consegui ver nada que pudesse ser.
Só por desencargo de conciência, dá um debug.print na quantidade de colunas da sua range. Veja o que aparece.

 
Postado : 30/05/2018 1:12 pm
(@ericksant)
Posts: 0
New Member
Topic starter
 

cara me desculpe pela ignorancia...

Como ficaria o debugprint da minha range ?

 
Postado : 30/05/2018 1:34 pm
(@xlarruda)
Posts: 0
New Member
 

Ative a janela de verificação imediata do VBA

e insira essa linha no seu código, depois rode ele

Debug.Print rangetoexport.Columns.Count

Verifique o resultado na janela de verificação e veja se é igual a 7 ( ou 11, não sei direito que resultado trará). Imagino eu que, se estiver retornando 3 é pq o erro está ai...

 
Postado : 30/05/2018 2:01 pm
(@ericksant)
Posts: 0
New Member
Topic starter
 

Fiz o teste aqui, está exatamente no range, não sei por qual motivo, ele só reconhece até o r3...

Os outros ranges criados não são lidos... Ainda não consigo entender o motivo...

 
Postado : 30/05/2018 2:09 pm
(@ericksant)
Posts: 0
New Member
Topic starter
 

Acho que entendi o motivo... As ranges devem estar em sequencia... Repara que ele pega N, O, P, a proxima seria uma letra para tras... Fiz um teste pegando a coluna seguiente, que seria a Q e foi...
Vou criar uma macro para organizar antes de fazer isso tudo e testar..

 
Postado : 30/05/2018 2:22 pm
(@xlarruda)
Posts: 0
New Member
 

kk faz sentido..

Uma sugestão seria mudar apenas a posição dos r's no Union:

 Set rangetoexport = Union(r7, r5, r4, r6, r1, r2, r3)
 
Postado : 30/05/2018 2:27 pm
(@ericksant)
Posts: 0
New Member
Topic starter
 

Consegui resolver, muito obrigado cara!

 
Postado : 30/05/2018 3:14 pm