我多次读过代码中应该避免使用GoTo,但是我经常需要创建循环,如果一个项目给我一个错误,代码就会停止。
在下面的例子中,我必须比较单元格值,但如果我在单元格中有字符串,则会出错。
对于以下代码,您还有其他选择来避免使用GoTo吗?
谢谢!
Sub Conditional()
Dim x As Integer
For x = 1 To 31
On Error GoTo na
If Sheets("Sheet1").Cells(8 + x, 5) >= 0.95 Then
Sheets("Sheet2").Shapes("Shape " & x).Fill.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Sheets("Sheet1").Cells(8 + x, 5) < 0.95 Then
Sheets("Sheet2").Shapes("Shape " & x).Fill.ForeColor.RGB = RGB(255, 0, 0)
End If
GoTo nextx
na:
Sheets("Sheet2").Shapes("Shape " & x).Fill.ForeColor.RGB = RGB(0, 0, 0)
On Error GoTo -1
nextx:
Next x
End Sub
答案 0 :(得分:4)
在这种情况下,如果要检查单元格中的字符串,则如下所示:
Sub Conditional()
Dim x As Long
For x = 1 To 31
If IsNumeric(Sheets("Sheets1").Cells(8 + x, 5)) Then
If Sheets("Sheet1").Cells(8 + x, 5) >= 0.95 Then
Sheets("Sheet2").Shapes("Shape " & x).Fill.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Sheets("Sheet1").Cells(8 + x, 5) < 0.95 Then
Sheets("Sheet2").Shapes("Shape " & x).Fill.ForeColor.RGB = RGB(255, 0, 0)
End If
End If
Next x
End Sub
通常,goto应仅用于捕获错误,例如On Error GoTo ErrorHandler
,没有排除。
答案 1 :(得分:1)
因为您正在进行一些格式化,具体取决于类型(text
或numbers
),然后您可以使用Range
Function GetCells(rng As Range, cellType As XlCellType, cellValues As XlSpecialCellsValue, outputRng As Range) As Boolean
On Error Resume Next '<--| ignore subsequent errors, if any
Set outputRng = rng.SpecialCells(cellType, cellValues) '<--| get a sub-range out of passed range as filtered by passed arguments
GetCells = Not outputRng Is Nothing '<--| returns 'True' if range has been properly set
End Function
方法对象并输入如下函数:
Sub Conditional()
Dim myCells As Range, cell As Range
With Sheets("Sheet 1").Range("E9:E39") '<--| reference your sheet relevant range
If GetCells(.Cells, xlCellTypeConstants, xlNumbers, myCells) Then '<--| if any cells whose value is a "constant" "number" in your range
For Each cell In myCells '<--| loop through those filtered cells
Sheets("Sheet2").Shapes("Shape " & cell.row - 8).Fill.ForeColor.RGB = IIf(cell.Value >= 0.95, RGB(0, 176, 80), RGB(255, 0, 0)) '<--| format your shapes as per corresponding current cell
Next cell
End If
If GetCells(.Cells, xlCellTypeConstants, xlTextValues, myCells) Then '<--| if any cells whose value is a "constant" "text" in your range
Sheets("Sheet2").Shapes("Shape " & cell.row - 8).Fill.ForeColor.RGB = RGB(0, 0, 0) '<--| format your shapes as per corresponding current cell
End If
End With
End Sub
并按如下方式利用它:
instance.constructor.name