加载数组值时VBA:错误9

我目前正在编写一个多用户表单工作簿,通过​​添加点来检查客户进入系统。 我试图通过让“Check In Form”中的主标签在登记时按名字对客人做出回应,从而使其更加个性化。我还制作了另一个用户表单,如果他们要求显示所有客人信息它。 现在我有2个关于我尝试通过其他在线资源debugging的问题。

1)在登记过程中,我使用一个名为Profile的数组来检索该人的所有信息。 当我调出要添加到数组的范围时,最终会出现错误9“下标超出范围”。 为了弥补这一点,我试图ReDim保存arrays,只是为了发现我的信息已被清除。

 Option Explicit Dim Profile() as Variant, Point as Integer Sub CheckIn() ActiveCell.Offset(0, 6).Select ActiveCell.Value = ActiveCell.Value + Point If ActiveCell.Value >= 10 Then ActiveCell.Value = ActiveCell.Value - 10 MsgBox ("Congradulations! You just earned one free Engineering Pad. Talk to your Membership chair to recieve your free pad.") End If ActiveCell.Offset(0, 1).Select ActiveCell.Value = ActiveCell.Value + Point Profile() = Array(Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row, 12))) 'data is Error 9 here ReDim Preserve Profile(0 To 11) 'data is cleared here MainLabel.Caption = "Hello " & Profile(1) & " " & Profile(2) & ". You Have " & Profile(7) & " Points." ActiveCell.EntireRow.Select Application.Wait (Now + #12:00:05 AM#) MainLabel.Caption = "Please Enter Your 9-Digit ID or Swipe Your Card" End Sub 

此外,即使在使用Split()时,将数据types从Variant更改为String也只会在将数据添加到Profile时产生types不匹配。 这怎么解决? 任何意见表示赞赏。 谢谢!

这是我的电子表格的图像

在这里输入图像说明

当您将一定范围的单元格中的值分配到variables数组中时,您总是会得到一个两维的基于1的数组; 即使该数组只是1到1作为第二个列(列),或者在您的情况下,在第一个列(行)中是1到1。

 dim profile as variant, acrw as long acrw = activecell.row with worksheets("MySheet1") 'know what worksheet you are on!!!!! profile = .Range(.Cells(acrw, 1), .cells(acrw, 12)).value2 'the following should be 1:1 and 1:12 debug.print lbound(profile, 1) & ":" & ubound(profile, 1) debug.print lbound(profile, 2) & ":" & ubound(profile, 2) 'why are you redimming this at all? 'ReDim Preserve Profile(0 To 11) 'the following adds room for two more columns of data while preserving the values ReDim Preserve Profile(1 to 1, 1 To 14) end with 

只能将ReDim语句与Preserve一起使用来更改第二个等级的维度; 从来没有第一次。

使用LBound和UBound函数来确定数组的限制( 又名边界)。

Range()不需要在它周围的Array()来获取值…另外,Range将始终生成一个单值或二维数组。

更改:

 Profile = Range(Cells(ActiveCell.Row, 1), Cells(ActiveCell.Row, 12)) 'note the lack of parentheses 

另外,由于行是第一个元素,所以不能用preserve保留数组,因为preserve只能在数组的最后一个维上运行。

ReDim Preserve Profile(0 To 11,0 to 2)将工作,但
ReDim Preserve Profile(0 To 22,0 to 1)将失败,因为在此上下文中保留无效