首页 > 解决方案 > “对象'范围'的方法'值'失败”错误的问题

问题描述

这是一个主要是为了理解和学习的问题,然后是为了找到解决方案,因为我知道导致问题的原因并提出了解决方法。

我收到运行时错误“-2147417848 (80010108)”:对象“范围”的方法“值”失败。

我有一个带有 ListBox 的主用户窗体,它是从表中填充的。然后我有一个辅助用户窗体在所述表中创建新条目。该表在我的工作表 shData("Datan") 上,称为“mainData”。如果只是运行辅助表单来创建新条目,一切都很好。但是,如果我从主表单开始辅助表单,我会收到错误消息。

这是主要形式的代码。

Private Sub newEntryButton_Click()
    newEntry.Show
End Sub

Private Sub UserForm_Activate()
    mainListUpdate
End Sub

这是二级形式的代码

Private Sub doneButton_Click()
    Dim n As Long
    n = cRow + 1
    shData.Range("A" & n).Value = nameBox.Value
    shData.Range("B" & n).Value = paraBox.Value
    shData.Range("C" & n).Value = hStartBox.Value
    shData.Range("D" & n).Value = bdayBox.Value
    If OptionButtonStat.Value = True Then
        shData.Range("E" & n).Value = "Ja"
        shData.Range("G" & n).Value = statPlaceBox.Value
    ElseIf OptionButtonAmb.Value = True Then
        shData.Range("F" & n).Value = "Ja"
    End If
    Me.Hide
End Sub
Private Sub OptionButtonStat_Change()
    If OptionButtonStat.Value = True Then
        Me.statPlaceBox.Visible = True
        Me.statPlaceLab.Visible = True
    Else
        Me.statPlaceBox.Visible = False
        Me.statPlaceLab.Visible = False
    End If
End Sub
Public Sub UserForm_Activate()
    Me.statPlaceBox.Visible = False
    Me.statPlaceLab.Visible = False
End Sub

这是模块中的代码。

Public cRow As Long
Public cCol As Long
Public Sub mainListUpdate()
    If shData.FilterMode = True Then
        shData.ShowAllData
    End If
    cRow = shData.Range("A1").CurrentRegion.Rows.Count 
    cCol = shData.Range("A1").CurrentRegion.Columns.Count
    formMain.listMain.ColumnCount = cCol
    formMain.listMain.ColumnHeads = True
    formMain.listMain.RowSource = "mainData"
End Sub

错误发生在次要格式代码中的以下行:shData.Range("A" & n).Value = nameBox.Value。如果我formMain.listMain.RowSource = "mainData"将模块代码更改为formMain.listMain.RowSource = "Daten!A2:G",问题就会消失。同样,代码可以很好地使用表作为 RowSource,如果我只使用辅助表单,只需添加cRow = shData.Range("A1").CurrentRegion.Rows.Count.

我希望,我解释得很好。有人可以解释一下,为什么我有这个问题?搜索问题非常令人沮丧,我真的很想使用原始代码。

标签: excelvba

解决方案


推荐阅读