Excel:即使有值,循环也不会执行所有动作

时间:2015-05-12 11:51:18

标签: excel vba

首先感谢您解决我的第一个问题。但是,在尝试执行公式/循环时,它会在end if之后立即转到if score > "0",即使分数实际上大于0(例如64)。

问题

我做错了什么?

Sub whatever()
    Dim score As Integer, sStart As Integer, sTeller As Integer, _
                          lcount As Integer, result As String
    sStart = Sheets("Packed").Range("F1").Value
    sTeller = Sheets("Packed").Range("E1").Value
    lcount = sStart
    score = Range("B" & lcount).Value

    Application.ScreenUpdating = False

    Do While lcount < sTeller
    Sheets("Packed").Select
    If score > "0" Then 'HERE!
      Range("A" & lcount & ":C" & lcount).Select
      Selection.Cut
      Sheets("data").Select
      Range("A5").Select
      Selection.End(xlDown).Select
      Selection.Offset(1, 0).Select
      ActiveSheet.Paste    
    End If
    lcount = lcount + 1
    Loop
    MsgBox "All values have been checked"

    Columns("D:F").Select
    Selection.Delete Shift:=xlToLeft

    Application.ScreenUpdating = True

End Sub

3 个答案:

答案 0 :(得分:0)

这是不正确的

if score > "0" Then

这是正确的:

if score > 0 Then

答案 1 :(得分:0)

试试这个版本

Sub WhatEver()

    Dim score As Integer
    Dim sStart As Integer
    Dim sTeller As Integer
    Dim lcount As Integer
    Dim result As String

    With ThisWorkbook.Worksheets("Packed")

        sStart = .Cells(1, 6)
        sTeller = .Cells(1, 5)
        lcount = sStart
        score = .Cells(lcount, 2)

        Do While lcount < sTeller
            If score > 0 Then
                .Range(.Cells(lcount, 1), .Cells(lcount, 3)).Cut _
                    Destination:=ThisWorkbook.Worksheets("Data").Cells(5, 1).End(xlDown)
            End If
            lcount = lcount + 1
        Loop

        MsgBox "All values have been checked."
        .Columns("D:F").Delete shift:=xlToLeft

    End With

End Sub

答案 2 :(得分:0)

  

当试图执行公式/循环时,它会立即进入&#34;如果&#34;在&#34;如果得分&gt;之后&#34; 0&#34;&#34;,即使得分实际上大于0

这是因为您在循环之前只设置了一次score = Range("B" & lcount).Value,并且每次score移动循环时都没有更新lcount。所以,将score = Range("B" & lcount).Value置于循环

这里是您更新的代码

Sub whatever()
Dim score As Integer, sStart As Integer, sTeller As Integer, lcount As Integer, result As String
sStart = Sheets("Packed").Range("F1").Value
sTeller = Sheets("Packed").Range("E1").Value
lcount = sStart

Application.ScreenUpdating = False

Do While lcount < sTeller
    Sheets("Packed").Activate
    score = Range("B" & lcount).Value
    If score > 0 Then
        Range("A" & lcount & ":C" & lcount).Cut
        Sheets("data").Activate
        Range("A" & Cells(Rows.Count, "A").End(xlUp).Row + 1).Paste
    End If
    lcount = lcount + 1
Loop

MsgBox "All values have been checked"

Columns("D:F").Delete Shift:=xlToLeft

Application.ScreenUpdating = True

End Sub

并且仅仅因为我看到该分数在循环之前仅更新了一次,我建议你不要在之前的问题中使用循环。