定义数组以获取范围内的数据为“double”vartypes

我对VBA相当陌生,请耐心等待。 我想告诉VBA从一系列单元格中获取数组。 用户将一列数据粘贴到单元格C2中,以便填充C2以下的单元格。 填充的单元格的数量取决于用户。

我也将需要在数组中的每个元素被视为双打,因为我要与他们进行操作。

因此,如果名单是

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 

谢谢!

Excel.ActiveWorkbook. 在Excel中是不需要的,这是隐含的。 我不需要input单元格值CDbl(.Cells(x, "C"))

在这里输入图像说明

 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 
 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 

你可以简单地去像下面这样

 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 

如果您需要处理Doubletypes的数组值,则可以使用CDbl()函数

在VBA中,您只能将.Value.Value2数组分配给Variant

作为一个旁注,如果范围是格式化的表,你可以做一些类似的事情

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