Excel运行简单的VBA代码时崩溃没有错误或指示原因?

时间:2017-01-09 11:29:41

标签: excel vba excel-vba

Excel已经开始崩溃而没有任何解释,而且代码以前有效,所以我不确定为什么它现在经常崩溃。它甚至没有那么多代码或非常复杂。我只是在两个单独的工作表中向表中添加新值。任何帮助将不胜感激!

表1:

Option Explicit
Private Sub CommandButton1_Click()

Dim nameStr As String
nameStr = TextBox1.Value
Dim costInt As Integer
costInt = TextBox2.Value

Dim newRateValues(8)
newRateValues(0) = nameStr
newRateValues(1) = costInt
newRateValues(2) = costInt
newRateValues(3) = costInt
newRateValues(4) = costInt
newRateValues(5) = costInt
newRateValues(6) = costInt
newRateValues(7) = costInt
newRateValues(8) = costInt

AddDataRow "ratesTable", newRateValues

AddDataRow2 "tableResources"
End Sub

模块:

Option Explicit
Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.count).Range
    For col = 1 To lastRow.Columns.count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

Sub AddDataRow2(tableName As String)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range
    Dim newRate As Integer

    Set sheet = ActiveWorkbook.Worksheets("Sheet2")
    Set table = sheet.ListObjects.Item(tableName)

    newRate = ActiveSheet.TextBox1.Text

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.count).Range
    lastRow.Cells(1, 2) = newRate 
End Sub

0 个答案:

没有答案