2016-08-24 70 views
2

我對VBA相當陌生,因此請耐心等待。 我想告訴VBA從一系列單元格中獲取數組。用戶將一列數據粘貼到單元格C2中,以便填充C2以下的單元格。填充的單元格數量取決於用戶。定義數組以獲取範圍內的數據爲「double」var類型

我也需要將數組中的每個元素都視爲雙打,因爲我將使用它們進行操作。

因此,如果該列表是

1.2222 
2.4444 
3.5555 

然後我需要的陣列保留小數點。 我該怎麼做? 這是我這有皮毛,沒有運氣:

Set ThisWS = Excel.ActiveWorkbook.Worksheets("Hoja1") 
Dim InputValues() As Double 'Define Array 
Dim LRow As Long    'Define length of array 
With Sheets("Hoja1") 
    LRow = .Range("C" & .Rows.count).End(xlUp).Row 
End With 
InputValues = ThisWS.Range("C2:C" & LRow).Value 'Error 13: data type doesn't match 
End Sub 

謝謝!

+1

你會需要數組'作爲Variant',這是加載到數組中唯一支持的類型。作爲其唯一的一列,您可以輕鬆地循環單元格並手動添加到雙精度數組中 –

+1

OT:請記住給出反饋 - 這是因爲我剛剛看到[此主題](http://stackoverflow.com/questions/) 39124058/vba-error-9-when-for-each-on-an-array) - 在你的每個問題上,標記答案和其他內容,否則,具有相同問題的另一個用戶將不知道什麼有幫助。 – Sgdva

回答

0
Set ThisWS = Excel.ActiveWorkbook.Worksheets("Hoja1") 
Dim CurRow As Long 
Dim LRow As Long    'Define length of array 
    LRow = ThisWS.Range("C" & Rows.count).End(xlUp).Row 
Dim InputValues(1 to LRow - 1) As Double 'Define Array 

For CurRow = 2 to LRow 
    InputValues(CurRow - 1) = ThisWS.Range("C" & CurRow).Value 
Next CurRow 
End Sub 
0

,你可以簡單地去像如下

Option Explicit 

Sub main() 
    Dim InputValues As Variant 'Define Array 

    With Excel.ActiveWorkbook.Worksheets("Hoja1") ' refer to wanted worksheet 
     InputValues = .Range("C2", .Cells(.Rows.Count, 3).End(xlUp)).value 'fill array with values in column "C" cells from row 2 down to last non emtpy one 
    End With 
End Sub 

應該你需要處理數組值Double型的,那麼你可以使用CDbl()功能在Excel中不需要

1

Excel.ActiveWorkbook. ,這是隱含的。我不需要鍵入單元格值CDbl(.Cells(x, "C"))

enter image description here

Sub Example() 
    Dim InputValues() As Double 
    Dim lastRow As Long, x As Long 

    With Worksheets("Hoja1") 
     lastRow = .Range("C" & .Rows.Count).End(xlUp).Row 

     ReDim InputValues(lastRow - 2) 

     For x = 2 To .Range("C" & .Rows.Count).End(xlUp).Row 
      InputValues(x - 2) = CDbl(.Cells(x, "C")) 
     Next 
    End With 

End Sub 

這個例子更有效,但除非你是一個非常大的數據量的工作不會讓一個明顯的區別。

Sub Example2() 
    Dim InputValues() As Double, vInputValues As Variant 
    Dim x As Long 

    With Worksheets("Hoja1") 
     vInputValues = .Range("C2", .Range("C" & .Rows.Count).End(xlUp)).Value2 

     ReDim InputValues(UBound(vInputValues) - 1) 

     For x = 1 To UBound(vInputValues) 
      InputValues(x - 1) = CDbl(vInputValues(x, 1)) 
     Next 
    End With 

End Sub 
+0

我更喜歡例子2。如果你不會發布,我會:) :) –

+0

@SiddharthRout謝謝。我認爲第一個例子的模式對大多數讀者來說會更加熟悉。 – 2016-08-24 18:12:49

+0

@Slai感謝您的編輯。 – 2016-08-24 18:15:04

0

在VBA中,你可以指定.Value.Value2陣列只有一個Variant

作爲一個側面說明,如果範圍被格式化爲表,你可以做這樣的事情

Dim InputValues() ' As Variant by default 
InputValues = [transpose(Hoja1!Table1[Column3])] ' Variant(1 to number of rows in Table1) 
相關問題