如果value = 0,则为Excel VBA,然后不进行目标搜索

时间:2016-10-18 07:20:21

标签: excel vba excel-vba macros

嗨,我是vba的新手,并且一整天都在寻找一种方法来完成这项工作。无论如何,我需要我的GoalSeek宏来影响列“EW”中的所有单元格,以便在“EX”>中的相邻单元格时调整EP的值。如果“EX”中相邻单元格的值= 0,则保留空白或将值更改为0.列“EP”“EW”和“EX”均相互影响值。下面是我拼凑的代码。我收到编译错误:如果没有结束则阻止

感谢您的帮助

    Private Sub CommandButton1_Click()

Dim StartTime As Double
Dim MinutesElapsed As String

'Remember time when macro starts
  StartTime = Timer


Dim lr As Long
Dim cell As Variant


Application.DisplayAlerts = False
Application.ScreenUpdating = False

    Range("A9").Select
        lr = Cells.Find("*", SearchORder:=xlByRows, SearchDirection:=xlPrevious).Row

For j = 9 To lr
   If Cells(j, "EX").Value > 0 Then
           Cells(j, "EP").GoalSeek Goal:=60, ChangingCell:=Cells(j, "EW")
               For Each cell In Range("EW9:EW" & lr)
                    cell.Value = WorksheetFunction.Round(cell.Value, 0)
                        Next cell

        Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Determine how many seconds code took to run
  MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

'Notify user in seconds
  MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation


End Sub

2 个答案:

答案 0 :(得分:0)

在文本之前

Application.DisplayAlerts = True
Application.ScreenUpdating = True

你需要写:

end if
next j

因此看起来像这样:

Next cell
end if
next j
Application.DisplayAlerts = True
Application.ScreenUpdating = True

答案 1 :(得分:0)

如错误消息所示,您在End If阻止结束时没有If。如果我了解你,那应该是在cell循环之后。您还需要放置Next j,以显示程序在哪里完成j循环的迭代。

Private Sub CommandButton1_Click()

Dim StartTime As Double
Dim MinutesElapsed As String
Dim lr As Long
Dim cell As Variant

'Remember time when macro starts
StartTime = Timer

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Range("A9").Select
lr = Cells.Find("*", SearchORder:=xlByRows, SearchDirection:=xlPrevious).Row

For j = 9 To lr
    If Cells(j, "EX").Value > 0 Then
        Cells(j, "EP").GoalSeek Goal:=60, ChangingCell:=Cells(j, "EW")
        For Each cell In Range("EW9:EW" & lr)
            cell.Value = WorksheetFunction.Round(cell.Value, 0)
        Next cell
    End If
Next j

Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Determine how many seconds code took to run
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

'Notify user in seconds
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation


End Sub