在循环中运行时错误91 – 看不到任何理由

这可能是相当明显的,但是我做了相当多的search引擎无济于事。

首先,如果你有一个更简洁的方法来做这件事,我会非常高兴,我总是渴望学习 – 这是我能想到的最好的方式来完成任务。

基本上,一旦find列,我将从另一个表格中传输数据,这些数据将在范围(xlDown)的末尾处移动,并被偏移1等。

但目前,如果我运行这个为1至6它工作正常,如果我运行1到7它给出了错误,但一切都以相同的方式定义。 strSoS​​已定义,但rngSoS始终显示为“Nothing”,即使其他单元格正常工作?

第1到第7列在String声明列表中有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 

您正试图将string地址(文本)填充到未分配的Range对象中 。

 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失败,因为它是唯一实际声明为范围typesvariables。