对于每个循环和偏移

时间:2018-02-09 18:56:45

标签: excel vba excel-vba if-statement foreach

我正在开发VBA中的代码,而我遇到的任务是在一个工作表中搜索字符串的范围;然后将字符串记录在同一行中,但为所有出现的事项留下一列(所以.offset(0,-1));然后它在另一个工作表中搜索每个记录的字符串,并将对应于记录的字符串的整数与该列的右侧相加。

Option Explicit
Option Base 1

Public Sub StoredProcTimes()
    Worksheets("Proc Time").Select
    Dim Table() As Variant, nItem As Integer
    Range("A2", Range("A2").End(xlDown).End(xlToRight)).Name = "ProcTime"
    nItem = Range("ProcTime").Rows.Count
    ReDim Table(nItem, 2)
End Sub

Public Sub DayLoad()
    Range("G2", Range("G1").End(xlDown)).Name = "Dates"
    Call StoredProcTimes
    Dim reply As Date, cell As Range, sum As Integer
    reply = InputBox("Specify Date", "Day Load", "9/1/2017")
    For Each cell In Range("Dates")
        If cell.Value = reply Then
            cell.Offset(0, -1).Value

        End If
    Next
    MsgBox "The load for " & reply & " is " & sum & " minutes"
End Sub

1 个答案:

答案 0 :(得分:1)

首先,您的专线cell.Offset(0, -1).Value并未做任何事情。你没有将它设置为等于一个值。你应该在这里收到错误。

我个人不喜欢使用Offset(),但使用并不是什么大不了的事。在我的例子中,我向您展示了一种我认为有利的替代方法。

对于您尝试查找的特定单元格,不要在该范围内循环,这需要处理器时间。使用Range.Find()

Public Sub DayLoad()

    Dim ws As Worksheet, rngG As Range

    ' You may need to change the index, or use "SheetName"
    Set ws = ThisWorkbook.Worksheets(1)
    Set rngG = ws.UsedRange.Columns("G")

    'Call keyword is unnecessary 
    Call StoredProcTimes

    Dim sReply As String, myCell As Range
    sReply = InputBox("Specify Date", "Day Load", "9/1/2017")
    If Not IsDate(sReply) Then Exit Sub

    ' Search for your date
    Set myCell = rngG.Find(sReply)

    ' If date was found, then copy the date to the left 1 col
    If Not myCell Is Nothing Then
        With myCell
            ws.Cells(.Row, .Column - 1) = .Value
        End With
    End If

End Sub
相关问题