[英]Run-time error '1004': Method 'Range' of object '_worksheet' failed
I am trying to write to a cell when a checkbox is marked using this sub 我正在尝试使用此子标记标记复选框时写入单元格
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
But if I just open the sheet and click the checkbox I get the Run-time error '1004': Method 'Range' of object '_worksheet' failed error. 但是,如果我只是打开工作表并单击复选框,则会收到运行时错误'1004':对象'_worksheet'的方法'Range'失败错误。
I defined the variables at the top of the module: 我在模块顶部定义了变量:
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim comment As String
Dim rown As Integer
And I set the variables when the workbook opens: 当工作簿打开时,我设置了变量:
Private Sub Workbook_Open()
rown = 3
comment = "F" & rown
Set ws1 = ThisWorkbook.Sheets("Rating test")
Set ws2 = ThisWorkbook.Sheets("Comments test")
End Sub
What is strange to me, if I first press a button with the following code in the module, I do not get the error anymore, even though it is the same code I put into the Workbook_open event: 令我感到奇怪的是,如果我首先按下模块中具有以下代码的按钮,即使我输入的是与Workbook_open事件相同的代码,也不会再收到该错误:
Sub First_Comment()
Set ws1 = ThisWorkbook.Sheets("Rating test")
Set ws2 = ThisWorkbook.Sheets("Comments test")
rown = 3
comment = "F" & rown
End Sub
Thanks for the help, I am a VBA novice! 感谢您的帮助,我是VBA新手!
You need to declare your global variables as Public
otherwise the Workbook_Open
will create and work on his own variables since they are out of his scope 您需要将全局变量声明为
Public
否则Workbook_Open
将创建并使用他自己的变量,因为它们不在他的范围内
Public ws1 As Worksheet
Public ws2 As Worksheet
Public comment As String
Public rown As Integer
You should just use ws1
directly 您应该直接使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.