我正在尝试实现以下代码,其中代码搜索特定单元格的两个工作表,然后选择整个列 - 以便稍后将其包含在图表中。我的问题是我一直收到以下错误:
运行时错误'91':
对象变量或未设置块变量
我试图在 SO 上查看可能修复错误的各种解决方案,但我尝试过的解决方案似乎都没有用。
错误发生在该行:
Sensor.EntireColumn.Select
我认为解决方案很简单,但对我来说似乎有些遥不可及。
Sub Desperation()
Dim Sensor As Range
Dim RequiredSensor As String
Dim SearchRange As Range
Set SearchRange = ActiveSheet.Range("D1", Range("D1").End(xlToRight))
'The RequiredSensor is a user input - What sensor the user wants to select
RequiredSensor = Worksheets("Home").Range("F18")
'Essentially, the code should search through DAQ 1 for the RequiredSensor.
Worksheets("DAQ 1").Activate
Set Sensor = SearchRange.Find(What:=RequiredSensor)
'If it does not find the sensor, then it should search DAQ 2 for the RequiredSensor
If Sensor Is Nothing Then
Worksheets("DAQ 2").Activate
Sensor.EntireColumn.Select
'Once the sensor has been found, it should select the entire column below it, ready to be put into a chart.
Else
Sensor.EntireColumn.Select
End If
End Sub
有时其他解决方案可以在几次运行中运行,然后它们突然在同一点上再次出现同样的错误。
我在代码中添加了注释,以解释我的思路以及我想要实现的目标。
答案 0 :(得分:1)
您的代码目前正在说"如果传感器什么都没有,那么选择它的整个列"这是不可能的。如果Sensor
什么都没有,那就选择 Nothing ...
If Sensor Is Nothing Then
Worksheets("DAQ 2").Activate
Sensor.EntireColumn.Select '// <~~ sensor doesn't exist??
'Once the sensor has been found, it should select the entire column below it, ready to be put into a chart.
Else
Sensor.EntireColumn.Select
End If
这可能是因为RequiredSensor
尚未找到:
Set Sensor = SearchRange.Find(What:=RequiredSensor)
'// If it isn't found, then Sensor isn't set
答案:
另一种方法是让用户手动选择范围:
If Sensor Is Nothing Then
Worksheets("DAQ 2").Activate
Set Sensor = Application.InputBox("Select Required Sensor", Type:=8)
Sensor.EntireColumn.Select
'Once the sensor has been found, it should select the entire column below it, ready to be put into a chart.
Else
Sensor.EntireColumn.Select
End If
答案 1 :(得分:1)
Sub SensorSelecter()
Dim Sensor As Range
Dim SearchRange As Range
Dim SearchRange2 As Range
Dim RequiredSensor As String
Application.ScreenUpdating = False
RequiredSensor = Worksheets("Home").Range("F18").Value
Worksheets("DAQ 1").Activate
Set SearchRange = ActiveSheet.Range("D1", Range("D1").End(xlToRight))
Set Sensor = SearchRange.Find(What:=RequiredSensor)
If Sensor Is Nothing Then
Worksheets("DAQ 2").Activate
Set SearchRange2 = ActiveSheet.Range("D1", Range("D1").End(xlToRight))
Set Sensor = SearchRange2.Find(What:=RequiredSensor)
Sensor.EntireColumn.Select
Else
Sensor.EntireColumn.Select
End If
Application.ScreenUpdating = True
End Sub
正如@Macro Man指出的那样,问题是SearchRange
没有搜索到正确的工作表。
谢谢@Macro Man