簡體   English   中英

如何從for循環變量分配單元格值

[英]How to assign cell value from a for loop variable

我正在嘗試編寫一個代碼,該代碼根據單元格中的空格從單個文本單元格創建數組。 然后,它應該遍歷每個數組值,並查看它等效於哪個字典鍵值。

之后,代碼進入工作表,根據活動單元格復制數據,然后粘貼到新的工作表中。 一切正常,除了我也想將字典鍵和數據一起粘貼。 我嘗試為變量分配鍵值並將范圍設置為鍵值。

我已經測試過,如果我寫:selection.value = 500,則將500輸入到選擇范圍內。 會喜歡任何幫助/指針。 謝謝!

Sub Macro2()

'Keyboard Shortcut: Ctrl p

Dim dict As Object
Dim search As String
Dim i As Integer
Dim interval_array As Variant
Dim interval As String
Dim paste As Range

Set dict = CreateObject("scripting.dictionary")

dict.Add Key:=500, Item:=1
dict.Add Key:=800, Item:=2
dict.Add Key:=1000, Item:=3
dict.Add Key:=2000, Item:=4
dict.Add Key:=3000, Item:=5
dict.Add Key:=4000, Item:=6
dict.Add Key:=5000, Item:=7
dict.Add Key:=6000, Item:=8
dict.Add Key:=7000, Item:=9
dict.Add Key:=8000, Item:=10
dict.Add Key:=9000, Item:=11
dict.Add Key:=10000, Item:=12
dict.Add Key:=12000, Item:=13
dict.Add Key:=14000, Item:=14
dict.Add Key:=16000, Item:=15
dict.Add Key:=18000, Item:=16
dict.Add Key:=20000, Item:=17
dict.Add Key:=22000, Item:=18
dict.Add Key:=24000, Item:=19
dict.Add Key:=26000, Item:=20
dict.Add Key:=28000, Item:=21
dict.Add Key:=30000, Item:=22
dict.Add Key:=32000, Item:=23

search = ActiveCell.Value
interval_array = Split(search, " ")

ActiveCell.Offset(2).Select
Range(Selection, Selection.End(xlDown).End(xlToRight)).Select
Selection.Copy
Worksheets("data_table").Activate
ActiveSheet.paste
ActiveCell.End(xlToRight).Select
Range(Selection, Selection.End(xlDown)).Offset(0, 2).Select

For Each word In interval_array
    For Each Key In dict
        'MsgBox (word)
        'MsgBox (key)
        If Key = word Then
            'interval = word.Value
             Selection.Value = word.Text
        Else
        End If
    Next
Next

End Sub  

要在VBA中使用Dictionary對象功能:

  1. 要檢查是否在dict對象中找到任何數組interval_array ,可以使用:

    If dict.exists(CLng(word)) Then

  2. 要從dict檢索Item ,可以使用:

    Selection.Value = dict(CLng(word))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM