我正在尝试使用此子
标记复选框时写入单元格Sub CheckBox7_Click()
If ws1.Shapes("Check Box 7").OLEFormat.Object.Value = 1 Then
ws2.Range(comment).Offset(0, 2).Value = "1"
Else
ws2.Range(comment).Offset(0, 2).Value = "0"
End If
End Sub
但是,如果我只是打开工作表并单击复选框,我会收到运行时错误' 1004':方法'范围'对象' _worksheet'失败的错误。
我在模块顶部定义了变量:
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim comment As String
Dim rown As Integer
我在工作簿打开时设置变量:
Private Sub Workbook_Open()
rown = 3
comment = "F" & rown
Set ws1 = ThisWorkbook.Sheets("Rating test")
Set ws2 = ThisWorkbook.Sheets("Comments test")
End Sub
对我来说很奇怪,如果我第一次按下模块中带有以下代码的按钮,我就不会再收到错误,即使它与我在Workbook_open事件中输入的代码相同:
Sub First_Comment()
Set ws1 = ThisWorkbook.Sheets("Rating test")
Set ws2 = ThisWorkbook.Sheets("Comments test")
rown = 3
comment = "F" & rown
End Sub
感谢您的帮助,我是VBA新手!
答案 0 :(得分:1)
您需要将全局变量声明为Public
,否则Workbook_Open
将创建并处理自己的变量,因为它们超出了他的范围
Public ws1 As Worksheet
Public ws2 As Worksheet
Public comment As String
Public rown As Integer
答案 1 :(得分:0)
您应该直接使用ws1
Sub CheckBox7_Click()
Set ws1 = ThisWorkbook.Sheets("Rating test")
If ws1.Shapes("Check Box 7").OLEFormat.Object.Value = 1 Then
ws2.Range(comment).Offset(0, 2).Value = "1"
Else
ws2.Range(comment).Offset(0, 2).Value = "0"
End If
End Sub