循环上的运行时错误91 - 看不出任何原因

时间:2015-12-29 15:00:27

标签: excel vba

这可能是非常明显的事情,但我做了很多谷歌搜索无济于事。

首先,如果你有更简洁的方法,我会非常高兴,我总是热衷于学习 - 这是我能想到的最好的方法来实现这个任务。

基本上,一旦找到列,我将从另一张表格中传输数据,该表格将在Range(xlDown)的末尾,并且偏移1等。

但是目前,如果我将其作为1到6运行它可以正常工作,如果我运行1到7它会给出错误但是所有内容都以相同的方式定义。定义了strSoS​​,但即使其他单元格工作正常,rngSoS也总是显示为“Nothing”?

第1列到第7列在字符串声明列表中有7个标题(如上所述),这样做的原因是表格数据来自可能有额外的列不需要。

希望你能帮我解决问题!

Sub ColumnSearch()

Dim strDoN, strOffice, strARN, strPIN, strAN, strAT, strSoS As String
Dim rngDoN, rngOffice, rngARN, rngPIN, rngAN, rngAT, rngSoS As Range

Dim myRange As Range
Dim NumCols, i As Integer

strDoN = "Date of Notification"
strOffice = "Office Centre"
strARN = "Appeal Reference Number"
strPIN = "PIN"
strAN = "Appellant Name"
strAT = "Appeal Type"
strSoS = "SoS Decision Date"



For i = 1 To 7
    If Cells(1, i).Value = strDoN Then
        rngDoN = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strOffice Then
        rngOffice = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strARN Then
        rngARN = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strPIN Then
        rngPIN = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strAN Then
        rngAN = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strAT Then
        rngAT = Cells(1, i).Address(False, False)
    ElseIf Cells(1, i).Value = strSoS Then
        rngSoS = Cells(1, i).Address(False, False)

    End If

Next i

MsgBox rngDoN & rngOffice & rngARN & rngPIN & rngAN & rngAT & rngSoS

End Sub

1 个答案:

答案 0 :(得分:3)

您正在尝试将字符串地址(文本)填充到未分配的Range object中。

Dim strDoN, strOffice As String, strARN As String, strPIN As String
Dim strAN As String, strAT As String, strSoS As String
Dim rngDoN As Range, rngOffice As Range, rngARN As Range
Dim rngPIN As Range, rngAN As Range, rngAT As Range, rngSoS As Range

For i = 1 To 7
    Select Case Cells(1, i).Value
        Case strDoN
            Set rngDoN = Cells(1, i)   '<~~ set the range object to this cell
        Case strOffice
            Set rngOffice = Cells(1, i)
        Case strARN
            Set rngARN = Cells(1, i)
        Case strPIN
            Set rngPIN = Cells(1, i)
        Case strAN
            Set rngAN = Cells(1, i)
        Case strAT
            Set rngAT = Cells(1, i)
        Case strSoS
            Set rngSoS = Cells(1, i)
        Case Else
            'no match - do nothing
    End Select
Next i

MsgBox rngDoN.Address(0, 0) & Chr(9) & rngOffice.Address(0, 0) & Chr(9) & _
       rngARN.Address(0, 0) & Chr(9) & rngPIN.Address(0, 0) & Chr(9) & _
       rngAN.Address(0, 0) & Chr(9) & rngAT.Address(0, 0) & Chr(9) & _
       rngSoS.Address(0, 0)

你的叙述对于你真正想要完成的事情来说有点短暂。我已将范围对象设置为匹配的单元格,并将其地址返回到消息框。

rngSoS失败了,因为它是唯一一个实际声明为范围类型变量的人。