我正在尝试编写一个简单的VBA代码,要求用户输入介于-9和+9之间的数字。用户输入数字后,代码将从与输入数字相关的特定列中的数据从一张纸中拉到新纸中。我已经写出了代码,但是If Else函数遇到问题。我收到一个错误,显示为“编译错误:语法错误”。如果我摆脱了Else函数,那么该代码对于大于或等于0的任何东西都适用,但是我需要具有提取与负输入相关的数据的能力。我不应该在代码中使用If Else吗?
Sub AA()
On Error Resume Next
er = Sheets("D2").Range("AA65536").End(xlUp).Row
ec = Range("IV1").End(xlToLeft).Column
r = 3
Range("A3:IV65536").ClearContents
For i = 504 To er
a = Sheets("D2").Cells(i, "AA")
If WorksheetFunction.IsErr(a) Then a = 0
If a >= Cells(2, 1).Value Then
For j = 2 To ec
f = Cells(1, j)
Cells(r, j) = Sheets("D2").Cells(i, f)
Next j
r = r + 1
Else a < Cells(2, 1).Value Then
For j = 2 To ec
f = Cells(1, j)
Cells(r, j) = Sheets("D2").Cells(i, f)
Next j
r = r + 1
End If
Next i
End Sub
答案 0 :(得分:3)
替换
Else a < Cells(2, 1).Value Then
具有:
Else
答案 1 :(得分:1)
使用:
使用 Elseif a
引用最后一行或最后一列的变量声明很久
无需使用错误恢复下一个
如果要循环范围,请对每个*使用*或*对于i = 1至*
代码准则:
Option Explicit
Sub Test()
Dim LastRow As Long, LastColumn As Long, Row As Long, Column As Long
Dim cell As Range, rng As Range
With ThisWorkbook.Worksheets("Sheet1") '<- Set the worksheet you want to use
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row '<- Find last row of column A sheet1
LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column '<- Find last column of row 7 sheet1
Set rng = .Range("A1:A" & LastRow) '<- Set range
'Method 1
For Each cell In rng
If cell.Value = 1 Then
ElseIf cell.Value = 2 Then
End If
Next cell
'Method 2
For Row = 2 To LastRow '<- Loop from row 2 to last row
For Column = 1 To LastColumn '<- Loop from column 1 to last column
Next Column
Next Row
End With
End Sub
答案 2 :(得分:0)
您是否尝试过摆脱Else
而仅使用另一个If
语句?同样,我将摆脱On Error Resume Next
,特别是如果您仍在测试代码。
Sub AA()
On Error Resume Next
er = Sheets("D2").Range("AA65536").End(xlUp).Row
ec = Range("IV1").End(xlToLeft).Column
r = 3
Range("A3:IV65536").ClearContents
For i = 504 To er
a = Sheets("D2").Cells(i, "AA")
If WorksheetFunction.IsErr(a) Then a = 0
If a >= Cells(2, 1).Value Then
For j = 2 To ec
f = Cells(1, j)
Cells(r, j) = Sheets("D2").Cells(i, f)
Next j
r = r + 1
End if
If a < Cells(2, 1).Value Then
For j = 2 To ec
f = Cells(1, j)
Cells(r, j) = Sheets("D2").Cells(i, f)
Next j
r = r + 1
End If
Next i
End Sub