如何修复运行时错误" 91"在Excel中

时间:2015-01-27 18:17:46

标签: vba excel-vba runtime-error excel

我创建了一个userform,可以为我输入数据到工作表中。我正在尝试编写它将信息放入选定工作表的位置。我有一个组合框,我可以在其中选择我希望它放入信息的工作表。我正在尝试将变量ws设置为组合框值并且我得到运行时错误' 91'它表示"对象变量或未设置块"。我遇到问题的代码如下。

Private Sub bttn_Submit_Click()
Dim iRow As Long
Dim ws As Worksheet

'set the variable for the worksheet
ws = ComboBox1.Value

'find first empty row in database
iRow = Columns("A").Find("*", SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1



'check for a date
If Trim(Me.txt_Date.Value) = "" Then
  Me.txt_Date.SetFocus
  MsgBox "Please enter a Date"
  Exit Sub
End If

'copy the data to the database
'use protect and unprotect lines,
'     with your password
'     if worksheet is protected
With ws
'  .Unprotect Password:="password"
  .Cells(iRow, 1).Value = Me.txt_Date.Value
  .Cells(iRow, 2).Value = Me.txt_Invoice.Value
  .Cells(iRow, 3).Value = Me.txt_Mileage.Value
  .Cells(iRow, 5).Value = Me.CheckBox_Oil_Filter
  .Cells(iRow, 7).Value = Me.CheckBox_Air_Filter
  .Cells(iRow, 9).Value = Me.CheckBox_Primary_Fuel_Filter
  .Cells(iRow, 11).Value = Me.CheckBox_Secondary_Fuel_Filter
  .Cells(iRow, 13).Value = Me.CheckBox_Transmission_Filter
  .Cells(iRow, 15).Value = Me.CheckBox_Transmission_Service
  .Cells(iRow, 17).Value = Me.CheckBox_Wiper_Blades
  .Cells(iRow, 19).Value = Me.CheckBox_Rotation_Rotated
  .Cells(iRow, 21).Value = Me.CheckBox_New_Tires
  .Cells(iRow, 23).Value = Me.CheckBox_Differential_Service
  .Cells(iRow, 25).Value = Me.CheckBox_Battery_Replacement
  .Cells(iRow, 27).Value = Me.CheckBox_Belts
  .Cells(iRow, 29).Value = Me.CheckBox_Lubricate_Chassis
  .Cells(iRow, 30).Value = Me.CheckBox_Brake_Fluid
  .Cells(iRow, 31).Value = Me.CheckBox_Coolant_Check
  .Cells(iRow, 32).Value = Me.CheckBox_Power_Steering_Check
  .Cells(iRow, 33).Value = Me.CheckBox_A_Transmission_Check
  .Cells(iRow, 34).Value = Me.CheckBox_Washer_Fluid_Check


'  .Protect Password:="password"
End With

'clear the data
Me.txt_Date.Value = ""
Me.txt_Invoice.Value = ""
Me.txt_Mileage.Value = ""
Me.txt_Date.SetFocus

End Sub

1 个答案:

答案 0 :(得分:1)

我拿你的代码并解释你的不一致性:

Dim ws As Worksheet
ws = ComboBox1.Value

第一行代码将ws声明为Worksheet对象。 VBA中的对象需要设置关键字Set,当然数据类型需要与声明匹配。

另一方面,在第二个声明中,您将ws设置为ComboBox1.Value,这是String类型。所以:

1)你得到错误的原因是ws是一个变量,由于它的声明,它希望获得一个Worksheet对象,但你反而试图投射一个其中String;

2)您可能想要做的是ws中包含名称为ComboBox1.Value 的Worksheet对象;在代码方面,这应该写成如下:

Set ws = ThisWorkbook.Sheets(ComboBox1.Value)

您只需要将行ws = ComboBox1.Value替换为上面的行。

一般情况下要注意:如果你声明一个 X 类型的变量,它将始终只能转换一个类型X 对象,除非你没有&#39 ; t声明它(非常糟糕的做法,你会在之后得到错误)。