“对象variables未设置”错误
我试图实现下面的代码,其中代码search特定单元格的两个工作表,然后select整个列 – 为了以后将其包括到图表中。 我的问题是,我不断收到以下错误:
运行时错误“91”:
对象variables或未设置块variables
我试图看看对于这个错误的可能修复的SO的各种解决scheme,但我没有试过的解决scheme似乎工作。
错误发生在线上:
Sensor.EntireColumn.Select
我认为解决scheme非常简单,但对我来说似乎有些遥不可及。
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
有时候,其他解决scheme只需要运行几次,然后他们突然莫名其妙地再次出现同样的错误。
我在代码中join了一些注释来解释我的思路和我想要达到的目标。
你的代码目前在说“如果传感器什么都没有,那么select它的整个列”这是不可能的。 如果Sensor
什么也没有,那么没有什么可以select的…
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
尚未find:
Set Sensor = SearchRange.Find(What:=RequiredSensor) '// If it isn't found, then Sensor isn't set
回答:
另一种方法是简单地让用户手动select范围:
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
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
没有search正确的工作表。
谢谢@macros手