Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

vba - Run-Time error 1004 Excel 2013

 Private Sub CommandButton1_Click()
 Dim lRow As Long
 Dim ws As Worksheet
 Set ws = Worksheets("Sheet2")
 lRow = ws.Cells(Rows.Count, 1).End(x1Up).Offset(1, 0).Row
 With ws
.Cells(lRow, 1).Value = UserForm1.TextBox1.Value
.Cells(lRow, 2).Value = UserForm1.TextBox2.Value
 End With
 End Sub

I am using this macro to add some entries into cells. I just want to add the 2 values into textboxes and the pressing the button to move the entries into Sheet2. Second time, the 2 entries will be moved below the first entry and so on...

Every time I am pressing the button I am getting the message "Run-Time error 1004".

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem has been expertly identified by mongoose36 but here is how to locate and address issues like this in the future.

Compile error: Variable not defined

Setting Require Variable Declaration within the VBE's Tools ? Options ? Editor property page will put the Option Explicit statement at the top of each newly created code sheet. This will avoid silly coding mistakes like misspellings as well as influencing you to use the correct variable type in the variable declaration. Variables created on-the-fly without declaration are all of the variant/object type.

??option_explicit
?????????Simple variable/constant misspelling compiler error (X1UP should be XLUP)

When you receive an error during run-time, go to the sub in the VBE and tap F8. The compiler will immediately issue a Compile error message and highlight the offending portion of the statement.

While this will not resolve all compile errors, it makes the simple mistakes quick and easy to identify and correct.

Addendum - Compile error: Syntax error

There is a special case involving misspelled variables that should be addressed. Declaration, assignment or use of a variable with a name that starts with a digit is illegal syntax. The Syntax error supersedes the Variable not defined error; there are two errors but the primary reported error is Syntax error. In this case the entire codeline is highlighted.

??option_explicit_number
?????????Variable misspelling compiler error with digit as first character(1ROW should be LROW)

You are writing good code with explicit parent worksheet references and not relying upon the implicit ActiveSheet property. Go one step further with the Require variable declaration option. Using Option Explicit is widely considered 'best practice'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...