我开始学习Excel中的VBA
编程,所以我的问题可能很基本。
我要做的就是:
1)获取我的代码以设置某个范围(行或列) 2)获取我的代码以创建具有该范围值的数组
想象一下,我在column A, from A1 to A50
中有一些数字。如果我选择单元格F7
(在下面的代码中为rng1
)并运行代码,我想获取数据A1:A7
(rng2
),Z5
会给我A1:A5
,依此类推。
我尝试的第一件事是:
Sub getdata()
Dim rng1 As Range 'This will be the selected cell
Dim rng2 As Range 'This will contain the data I want to retrieve
Dim data() As Variant 'And this will be the data
' Define the ranges
Set rng1 = Selection
Set rng2 = Range(Cells(1, 1), Cells(rng1.Row, 1))
'Get data
data = rng2.Value
Stop
End Sub
出于某种原因创建了树形结构,而不是一维数组。
我想轻松地处理数据,因此我通过以下过程在Internet上查找并找到了解决方法:
Sub SubValuesFromRange()
Dim someRange As Range
Dim someValues As Variant
Set someRange = Selection
With someRange
If .Cells.Count = 1 Then
ReDim someValues(1 To 1)
someValues(1) = someRange.Value
ElseIf .Rows.Count = 1 Then
someValues = Application.Transpose(Application.Transpose(someRange.Value))
ElseIf .Columns.Count = 1 Then
someValues = Application.Transpose(someRange.Value)
Else
MsgBox "someRange is multi-dimensional"
End If
End With
Stop
End Sub
此过程本身可以正常工作。如果选择A1:A5
并运行它,它将获取数据。如果我连续尝试也可以。
因此,我尝试从中创建一个函数,该函数可以在我的主过程中使用,这对以后的编程非常有用。
这里是代码和功能:
Sub getdata()
Dim rng1 As Range 'This will be the selected cell
Dim rng2 As Range 'This will contain the data I want to retrieve
Dim data() As Variant 'And this will be the data
' Define the ranges
Set rng1 = Selection
Set rng2 = Range(Cells(1, 1), Cells(rng1.Row, 1))
'Get data, this time throug the function
data = ValuesFromRange(rng2)
Stop
End Sub
Function ValuesFromRange(someRange)
Dim someValues As Variant
With someRange
If .Cells.Count = 1 Then
ReDim someValues(1 To 1)
someValues(1) = someRange.Value
ElseIf .Rows.Count = 1 Then
someValues = Application.Transpose(Application.Transpose(someRange.Value))
ElseIf .Columns.Count = 1 Then
someValues = Application.Transpose(someRange.Value)
Else
MsgBox "someRange is multi-dimensional"
End If
End With
End Function
然后...我收到一个错误:
数字13,类型不匹配
知道为什么吗?
是否可以使用一种更简单的方法将Excel数据导入VBA
?