2016-08-24 66 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) 
相关问题