Vba 初始化变量时Excel Visual Basic运行时错误“1004”
我正在学习VisualBasic,我使用的这个脚本在初始化变量I时出现了一个错误 我不确定问题出在哪里,但我收到了错误消息: 运行时错误“1004”:应用程序定义的错误或对象定义的错误 这是我的密码:Vba 初始化变量时Excel Visual Basic运行时错误“1004”,vba,excel,initialization,Vba,Excel,Initialization,我正在学习VisualBasic,我使用的这个脚本在初始化变量I时出现了一个错误 我不确定问题出在哪里,但我收到了错误消息: 运行时错误“1004”:应用程序定义的错误或对象定义的错误 这是我的密码: Sub excelmacro() Sheets("Sheet1").Select Range("A1").Select Sheets("Sheet2").Select Range("B1").Select i = 1 While i <> 10 If Len(Activ
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
您不需要在代码中使用变量i!把线踢出去就行了 循环中使用i的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
这可能是开始练习中详细介绍的方法的好时机 您的代码重复从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
我保留了您对工资使用的字符串变量,尽管使用double类型的变量并使用CDbl包装器转换文本可能会更好。已更正第二次使用xdesig而不是xdesignation。如果调试指向i=1行,则错误应为编译错误:未定义变量。如果在模块工作表顶部指定Option Explicit,但在使用变量(如Dim i)之前未声明变量,则会发生这种情况。我没有指定Option Explicit Though,但在设置值为1之前,我将Dim i设置为1时,该行也会出现同样的错误