2016-11-07 63 views
0

我想從excel中導出json文件,json文件基本上包含一個單獨的對象,其中包含大量的鍵和值。行D將是關鍵並且它的偏移將是該值。我想在每個結束行添加逗號(如果鍵),但我不知道如何停止在鍵尾添加逗號。我正在嘗試檢查範圍的最後一項,但顯然我未能匹配條件,因此每行都顯示逗號。如果有人能幫我一把,我真的很感激。這裏是我的代碼:我如何檢查範圍的行結束?

Dim encodedData As String 
Dim data As String 

Dim fso As Object 
Set fso = CreateObject("Scripting.FileSystemObject") 

Dim f As Object 
Set f = fso.CreateTextFile(Application.ActiveWorkbook.Path & "\exports\zh-CN.json", True, True) 

Dim rng As Range 
Set rng = Range(Sheets(1).Range("D2"), Sheets(1).Range("D2").End(xlDown)) 'use this for dynamic range 

f.Write "{" + Chr(10) 
For Each cell In rng 
    f.Write Chr(34) + cell.Value + Chr(34) + ": " + Chr(34) + cell.Offset(0, 5).Value + Chr(34) 

    If Cells(Rows.Count, "D").End(xlDown).Row <> cell.Row Then 
     f.Write "," + Chr(10) 
    Else 
     f.Write Chr(10) 
    End If 

Next 

f.Write "}" + Chr(10) 
f.Close 

回答

0

我想通了,我必須要找到的行數,並將其與當前行的單元格向下移動到比較,這裏的完整的解決方案:

Dim currentRow As String 
Dim lastRow As String 

Dim myWorksheet As Object 
Set myWorksheet = Worksheets("Sheet1") 
myWorksheet.UsedRange 

Dim fso As Object 
Set fso = CreateObject("Scripting.FileSystemObject") 

Dim f As Object 
Set f = fso.CreateTextFile(Application.ActiveWorkbook.Path & "\exports\zh-CN.json", True, True) 

Dim rng As Range 
Set rng = Range(Sheets(1).Range("D2"), Sheets(1).Range("D2").End(xlDown)) 'use this for dynamic range 

f.Write "{" + Chr(10) 
For Each cell In rng 
    f.Write Chr(34) + cell.Value + Chr(34) + ": " + Chr(34) + cell.Offset(0, 5).Value + Chr(34) 

    currentRow = cell.Row 
    lastRow = myWorksheet.UsedRange.Row + myWorksheet.UsedRange.Rows.Count - 1 

    If currentRow <> lastRow Then 
     f.Write "," + Chr(10) 
    Else 
     f.Write Chr(10) 
    End If 

Next 

f.Write "}" + Chr(10) 
f.Close