Excel VBA - Excel打开时的代码中断

时间:2015-03-20 06:54:50

标签: excel vba excel-vba

我发现我的代码问题,昨天没有出现。 这是“Sheet1(计算器)”中的代码:

Option Explicit

Private Sub Worksheet_Activate()
    Sheets("Calculator").ComboBox1.ListFillRange = "Materials!B4:B7"
    Sheets("Calculator").ComboBox1.ListIndex = 0
End Sub

Private Sub ComboBox1_Change()
Sheets("Calculator").Range("T18") = ComboBox1.ListIndex + 1
Select Case Sheets("Calculator").ComboBox1.ListIndex
    Case 0
        Sheets("Calculator").ComboBox2.ListFillRange = "Materials!G4:G5"
        Sheets("Calculator").ComboBox2.ListIndex = 0
    Case 1
        Sheets("Calculator").ComboBox2.ListFillRange = "Materials!G6"
        Sheets("Calculator").ComboBox2.ListIndex = 0
    Case 2
        Sheets("Calculator").ComboBox2.ListFillRange = "Materials!G7:G10"
        Sheets("Calculator").ComboBox2.ListIndex = 0
    Case 3
        Sheets("Calculator").ComboBox2.ListFillRange = "Materials!G11:G12"
        Sheets("Calculator").ComboBox2.ListIndex = 0
End Select
End Sub

一切正常,Excel打开时。但是,如果我保存并关闭Excel然后重新打开它,代码会在“案例0”下的第一行打破并显示错误消息:

Run-time error '438'
Object doesn't support this property or method

然后当我停止debuging并更改ComboBox1中的项目时,代码再次正常工作,并且ComboBox2充满了正确的数据。你有什么想法可以成为问题吗?

Here is the file.

2 个答案:

答案 0 :(得分:0)

不知道你是否正确初始化了你的ComboBox对象.....但这应该有效:

Set ComboBox1 = Sheets("Calculator").Shapes(1)
ComboBox1.ControlFormat.ListFillRange = "Materials!B4:B7"

所以可能是因为主要是你缺少ControlFormat的东西!?

答案 1 :(得分:0)

Private Sub ComboBox1_Change()
  with Sheets("Calculator")
   .Range("T18") = ComboBox1.ListIndex + 1
   if .ComboBox1.ListIndex > -1 Then .ComboBox2.List=sheets("Materials").range(G4:G5").offset(choose(.ComboBox1.ListIndex+1).value
  end with
End Sub