我对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
谢谢!
答案 0 :(得分:1)
Excel.ActiveWorkbook.
。我没有必要输入转换单元格值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
答案 1 :(得分: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
答案 2 :(得分: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()
函数
答案 3 :(得分:0)
在VBA中,您只能将.Value
和.Value2
数组分配给Variant
作为旁注,如果范围形成为表格,您可以执行类似
的操作Dim InputValues() ' As Variant by default
InputValues = [transpose(Hoja1!Table1[Column3])] ' Variant(1 to number of rows in Table1)