为什么我在 Excel 中使用 VBA 从字典中写入键和值时遇到困难?

问题描述 投票:0回答:1

我想将字典的键和值写入名为 dash 的 Excel 工作表中的单元格。然而,当我运行下面的代码时,它只在第 20 列中写入 nome1 ,而没有相应的值。当我第二次运行代码时,它正确填写了所有数据。

发生这种情况的原因是什么?可能的解决方案是什么?


Sub escreverDicionario()
    Dim dict As Object
    Dim wsdash As Worksheet
    Dim linha_inicial As Long
    Dim chave As Variant

    ' Definir a planilha de destino
    Set wsdash = ThisWorkbook.Sheets("dash")
    
    ' Criar o dicionário
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' Adicionar dados ao dicionário
    dict.Add "nome1", "valor1"
    dict.Add "nome2", "valor2"
    dict.Add "nome3", "valor3"
    
    ' Inicializar linha_inicial para 1
    linha_inicial = 1
    
    ' Loop para escrever os dados no Excel
    For Each chave In dict.Keys
        wsdash.Cells(linha_inicial, 20).Value = chave
        wsdash.Cells(linha_inicial, 21).Value = dict(chave)
        
        ' Avançar para a próxima linha
        linha_inicial = linha_inicial + 1
    Next chave
End Sub

我希望它从第一次执行代码时就可以正确编写,或者建议另一种可能的解决方案。

excel vba dictionary office365 spreadsheet
1个回答
0
投票

OP 的原始代码在我的机器上完美执行。 工作簿可能已损坏,或者单元格字体颜色可能与其内部颜色相匹配。

我只是想展示另一种转储键/值对的方法。

Sub escreverDicionario()
    Dim dict As Object
    Dim wsdash As Worksheet
    Dim linha_inicial As Long
    Dim chave As Variant

    ' Definir a planilha de destino
    Set wsdash = ThisWorkbook.Sheets("dash")
    
    ' Criar o dicionário
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' Adicionar dados ao dicionário
    dict.Add "nome1", "valor1"
    dict.Add "nome2", "valor2"
    dict.Add "nome3", "valor3"
    
    With wsdash
        .Cells(1, 20).Resize(dict.Count).Value = WorksheetFunction.Transpose(dict.Keys)
        .Cells(1, 21).Resize(dict.Count).Value = WorksheetFunction.Transpose(dict.Items)
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.