How to find max and min date in a range of another sheet?

前端 未结 2 1473
一个人的身影
一个人的身影 2020-12-19 16:23

I am writing VBA code to find the minimum and maximum dates in a Range. When I execute it, I get an error:

Run-time error \'1004\': Application-define

2条回答
  •  悲&欢浪女
    2020-12-19 16:54

    You better change a few aspects of your code, despite not all of them being responsible for the error you get. They make, in general, your code more prone to errors (for instance, when changing code or applying it to other cases).

    1. Use of Dim: Dim ssrRng, DestRange As Range declares ssrRng as Variant, and DestRange as Range. You should use Dim ssrRng As Range, DestRange As Range, assuming you want both as ranges.

    2. Use variables instead of explicit references, in particular if those are repeated. Use
      Dim ws as Worksheet
      Set ws = Workbooks().Sheets("Data")
      numAssignments = ws...
      instead of
      numAssignments = Sheets("Data")...

    3. Fully qualify the ranges you use, unless you explicitly do not want that.

      • Replace
        numAssignments = Sheets("Data")... with, e.g.,
        numAssignments = Workbooks().Sheets("Data")...
        (or, better, follow point 2, which already considers this point).
      • Replace
        EndDate = WorksheetFunction.Max(Sheets("Data").Range(Cells(2, 8), Cells(numAssignments, 8))) with
        EndDate = WorksheetFunction.Max(ws.Range(ws.Cells(2, 8), ws.Cells(numAssignments, 8)))
        Likewise for StartDate. In this case, these lines were the source of error, since Cells without qualifier works in the ActiveSheet.
    4. Avoid using Select, unless you explicitly need it. Declare and Set variables, and use them for referencing Ranges or Objects you want to work with.

提交回复
热议问题