簡體   English   中英

使用VBA將單元格值范圍分配給變量數組

[英]Using VBA to assign range of cell values to array of variables

我對VBA很新,要在這里忍受我。

我想給一組變量分配一組范圍的值,即。 運行簡短的代碼來簡化以下內容

Dim Sample 1 as string
Sample1 = activeworksheet.range("C17").value

Dim Sample 2 as string
Sample2 = activeworksheet.range("C18").value}

等等

在excelfunctions.net教程之后,我知道我可以縮短聲明

Dim Sample(1 to 20) as a string

但是教程將其刪除(因為它是關於名稱的教程),建議我按如下方式填充它

sample(1)=activesheet.range("C7").value
sample(2)=activesheet.range("C7").value

等等

我發現下面的討論是在正確的軌道上回答我的任務,但我無法應用它來解決我的問題。 循環的Excel VBA數組范圍

作為后續注釋,我最終嘗試為這些變量賦值,以便在以下過程中使用,而不是每次都聲明和分配它們。

謝謝!

嘗試這樣的事情:

Sub test()
Dim sampleArr(1 To 20) As String
Dim i As Integer
Dim rng As Range, cel As Range

i = 1
Set rng = Range("C1:C20") 

For Each cel In rng
    sampleArr(i) = cel.Value
    i = i + 1
Next cel
For i = LBound(sampleArr) To UBound(sampleArr)
    Debug.Print sampleArr(i)
Next i

此外,如果您知道要放入數組的范圍,則只需將數組設置為該范圍:

Sub test()
Dim sampleArr() As Variant
Dim i As Integer
Dim rng As Range, cel As Range

i = 1
Set rng = Range("C1:C20") ' Note, this creates a 2 Dimensional array

sampleArr = rng ' Right here, this sets the values in the range to this array.

For i = LBound(sampleArr) To UBound(sampleArr)
    Debug.Print sampleArr(i, 1) ' you need the ",1" since this is 2D.
Next i

End Sub

你應該 :

  • 定義要檢索數據的范圍
  • 對於該范圍的每個單元格,檢索您的數據

     dim tab() As string, cell as range, i as integer i = 0 redim tab(0) for each cell in ActiveWorksheet.Range("C1:C20") tab(i) = cell i = i + 1 redim preserve tab(i) next 

編輯:我縮進代碼以正確顯示它

以上的其他方式你只能使用:

Arr = ActiveWorksheet.Range("C1:C20").Value

然后你可以直接使用:

Arr(i,1)其中i是C1到C20范圍!

暫無
暫無

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

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