如何查看Range的行尾?

时间:2016-11-07 08:56:20

标签: vba excel-vba excel

我正在尝试从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

1 个答案:

答案 0 :(得分: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