初始化variables时,Excel Visual Basic运行时错误“1004”

我正在学习Visual Basic,我正在使用的这个脚本在初始化variablesi时会出现一个错误。

我不知道是什么问题,但我收到错误消息:

运行时错误“1004”:应用程序定义或对象定义的错误

这是我的代码:

 Sub excelmacro() Sheets("Sheet1").Select Range("A1").Select Sheets("Sheet2").Select Range("B1").Select i = 1 While i <> 10 If Len(ActiveCell.Value) > 1 Then Sheets("Sheet1").Select xname = Right(ActiveCell.Value, Len(ActiveCell.Value) - 6) xsalary = Right(ActiveCell.Value, Len(ActiveCell.Offset(2, 0).Value) - 8) xdesignation = Right(ActiveCell.Value, Len(ActiveCell.Offset(1, 0).Value) - 13) Sheets("Sheet2").Select ActiveCell.Value = xname ActiveCell.Offset(0, 1).Value = xdesig ActiveCell.Offset(0, 3).Value = xsalary ActiveCell.Offset(1, 0).Select Sheets("Sheet1").Select ActiveCell.Offset(3, 0).Select Else i = 10 End If Wend End Sub 

无论如何,你不需要variables我在你的代码! 只是踢线初始化我出。

在你的循环使用我的if语句基本上是逃避循环,可以缩短为:

 While Len(ActiveCell.Value) > 1 Sheets("Sheet1").Select xname = Right(ActiveCell.Value, Len(ActiveCell.Value) - 6) xsalary = Right(ActiveCell.Value, Len(ActiveCell.Offset(2, 0).Value) - 8) xdesignation = Right(ActiveCell.Value, Len(ActiveCell.Offset(1, 0).Value) - 13) Sheets("Sheet2").Select ActiveCell.Value = xname ActiveCell.Offset(0, 1).Value = xdesig ActiveCell.Offset(0, 3).Value = xsalary ActiveCell.Offset(1, 0).Select Sheets("Sheet1").Select ActiveCell.Offset(3, 0).Select Wend 

这可能是开始练习“ 如何避免在Excel VBAmacros中使用select”中详细介绍的方法的好时机。

您的代码重复从ActiveCell检索不同长度的最右侧字符,但使用活动单元格下方行中的值的长度来确定要检索的字符数。 看来你应该从你用来确定长度的同一个单元中检索字符。

 Sub excelmacro() Dim i As Long, xname As String, xsalary As String, xdesignation As String With Sheets("Sheet1") For i = 1 To .Cells(Rows.Count, "A").End(xlUp).Row Step 3 If CBool(Len(.Cells(i, "A").Value)) Then xname = Right(.Cells(i, "A").Value, Len(.Cells(i, "A").Value) - 6) xdesignation = Right(.Cells(i + 1, "A").Value, Len(.Cells(i + 1, "A").Value) - 13) xsalary = Right(.Cells(i + 2, "A").Value, Len(.Cells(i + 2, "A").Value) - 8) With Sheets("Sheet2") .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0) = xname .Cells(Rows.Count, "B").End(xlUp).Offset(0, 1) = xdesignation .Cells(Rows.Count, "B").End(xlUp).Offset(0, 3) = xsalary End With End If Next i End With End Sub 

尽pipe通过使用doubletypes的variables并使用CDbl()包装器转换文本,可能会更好地满足您对stringvariables的使用。 第二次使用xdesig而不是xdesignation修正了