如何在此代码中解决下标超出范围

时间:2019-03-28 14:47:19

标签: excel vba

我正在与用户窗体一起在表“ t_database”中添加数据。对于每个复选框= true,添加一个ROW。 当我添加一些数据时,出现“运行时错误'9'下标超出范围。.

要创建此代码,我使用了在此建立的帖子,并完成了我的要求。

Option Explicit
Private Sub cmdAddproject_Click()
Dim chkCnt As Integer
Dim ctl As MSForms.Control, i As Integer, lr As Long
Dim cb As MSForms.CheckBox

With Me
    chkCnt = .Tool1.Value + .Tool2.Value + .Tool3.Value + .Tool4.Value + .Tool5.Value + .Tool6.Value + .Tool7.Value + .Tool8.Value + .Tool9.Value + .Tool10.Value + .Tool11.Value + .Tool12.Value + .Tool13.Value + .Tool14.Value + .Tool15.Value + .Tool16.Value + .Tool7.Value + .Tool18.Value + .Tool19.Value + .Tool20.Value + .Tool21.Value + .Tool22.Value + .Tool23.Value + .Tool24.Value + .Tool25.Value + .Tool26.Value + .Tool27.Value + .Tool28.Value + .Tool29.Value + .Tool30.Value
    chkCnt = Abs(chkCnt)

    If chkCnt <> 0 Then
        ReDim mval(1 To chkCnt, 1 To 17)
        i = 1

        For Each ctl In .Controls
            If TypeOf ctl Is MSForms.CheckBox Then
                Set cb = ctl
                If cb Then
                    mval(i, 1) = .txtProyecto.Value
                    mval(i, 2) = .txtAno.Value
                    mval(i, 3) = .txtEmpresa.Value
                    mval(i, 4) = .SectorEmpresa.Value
                    mval(i, 5) = .TipoEmpresa.Value
                    mval(i, 6) = .txtDireccion.Value
                    mval(i, 7) = .txtCiudad.Value
                    mval(i, 8) = .txtCodigoPostal.Value
                    mval(i, 9) = .txtPais.Value
                    mval(i, 10) = .txtDescripcion.Value
                    mval(i, 11) = .txtIndicador1.Value
                    mval(i, 12) = .metrica1.Value
                    mval(i, 13) = .txtIndicador2.Value
                    mval(i, 14) = .metrica2.Value
                    mval(i, 15) = cb.Caption
                    mval(i, 16) = .txtAhorrosPrevistos.Value
                    mval(i, 17) = .txtAhorrosObtenidos.Value
                    i = i + 1
                End If
            End If
        Next
    End If
End With

With Sheets("Database")
    lr = .Range("A" & .Rows.Count).End(xlUp).Row + 1
    .Range("A" & lr).Resize(UBound(mval, 1), 17) = mval
End With
End Sub

0 个答案:

没有答案