例如,我在 excel 表“MySheet”中有一些資料,如下所示:
| 萼片 | 花瓣 |
|---|---|
| 5 | 11 |
| 4 | 12 |
| 3 | 13 |
在呼叫名為ex_dict ()的 VBA 函式后,我需要將這些資料轉換為類似字典的以下內容:
=ex_dict(A1:B4)
{"sepal": [5,4,3], "petal": [11,12,13]}
uj5u.com熱心網友回復:
列到字串
Function ex_dict(ByVal rg As Range) As String
Dim rCount As Long: rCount = rg.Rows.Count
If rCount < 2 Then Exit Function
ex_dict = "{"
Dim crg As Range
Dim r As Long
For Each crg In rg.Columns
ex_dict = ex_dict & """" & crg.Cells(1).Value & """: ["
For r = 2 To rCount
ex_dict = ex_dict & crg.Cells(r).Value & ","
Next r
ex_dict = Left(ex_dict, Len(ex_dict) - 1) & "], "
Next crg
ex_dict = Left(ex_dict, Len(ex_dict) - 2) & "}"
End Function
uj5u.com熱心網友回復:
使用字典物件。
Sub Example()
'Create a Dictionary object
Dim sepal As Object
Set sepal = CreateObject("Scripting.Dictionary")
'Loop through the table
Dim Cell As Range
For Each Cell In Range("A2:A5")
'Add unique entries to the dictionary
If Not sepal.exists(CStr(Cell.Value)) Then
'Add cell value as the Key & the adjacent value as the Item.
sepal.Add CStr(Cell.Value), Cell.Offset(, 1).Value
End If
Next
Debug.Print sepal("4") 'returns 12
Debug.Print sepal("3") 'returns 13
End Sub
uj5u.com熱心網友回復:
我沒有得到問題?
在 VBA 中使用函式 cells() 應該允許您通過給出單元格坐標來獲取值。一兩個 for...next 回圈也應該是讀取所有資料所必需的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461445.html
上一篇:VBA保存二進制
下一篇:無法使用VBA打開文本檔案
