为什么在我的电子表格中分配参考有时会起作用,有时甚至不行?

我在excel工作簿中有几个单元格,可以让客户端使用他自己的值。 我希望工作簿使用默认值初始化这些单元格。 为了做到这一点,我有一个工作表“Arkusz do makr”,我存储的价值。

在模块“GM”中,我声明了一个variables来引用我的工作表,就像这样:

Public M As Worksheet 

然后我初始化这个variables并设置我的默认值(在ThisWorkbook中):

 Private Sub Workbook_Open() Set M = Worksheets("Arkusz do makr") Worksheets("Values").Range("Value1") = M.Range("Value1") Worksheets("Values").Range("Value2") = M.Range("Value2") Worksheets("Values").Range("Value3") = M.Range("Value3") `etc End Sub 

现在有时候这个工作就像一个魅力,有时候,当我打开工作簿时,我会得到一个

运行时错误“91”:对象variables或块variables未设置。

有人可以向我解释这个行为吗? 此外,我想问一下,我的方法是否有意义,因为我很难把握事件的顺序以及事件的范围。

编辑:另外我应该提到的debuggingfunction强调我的代码中的第一个Worksheets...行。 在具体的工作表中,我也引用了M对象,尽pipe我认为它在这里改变了任何东西…

试着改变这个Sub的代码,如下所示。

我添加了一个简单的error handling – 如果工作簿中没有工作表“Arkusze do makr”或“Values”,则会显示警告消息,并且不会复制默认值。

你可以在代码中find更多的评论。

 Private Sub Workbook_Open() Dim macrosSheet As Excel.Worksheet Dim valuesSheet As Excel.Worksheet '------------------------------------------------------------------ With ThisWorkbook 'This command is added to prevent VBA from throwing 'error if worksheet is not found. In such case variable 'will have Nothing as its value. Later on, we check 'the values assigned to those variables and only if both 'of them are different than Nothing the code will continue. On Error Resume Next Set macrosSheet = .Worksheets("Arkusz do makr") Set valuesSheet = .Worksheets("Values") On Error GoTo 0 'Restore default error behaviour. End With 'Check if sheets [Values] and [Arkusz do makr] have been found. 'If any of them has not been found, a proper error message is shown. 'In such case default values are not set. If valuesSheet Is Nothing Then Call VBA.MsgBox("Sheet [Values] not found") ElseIf macrosSheet Is Nothing Then Call VBA.MsgBox("Sheet [Arkusz do makr] not found") Else 'If both sheets are found, default values are copied 'from [Arkusz do makr] to [Values]. 'Note that if there is no Range named "Value1" (or "Value2" etc.) 'in any of this worksheet, another error will be thrown. 'You can add error-handling for this case, similarly as above. With valuesSheet .Range("Value1") = macrosSheet.Range("Value1") .Range("Value2") = macrosSheet.Range("Value2") .Range("Value3") = macrosSheet.Range("Value3") End With End If End Sub