How to make match() work with date in excel vba?

后端 未结 6 672
萌比男神i
萌比男神i 2021-01-13 04:16

I\'m having problem making the match() work in excel VBA. The code is:

x = Application.Match(\"Sep 2008\", Range(\"F1:F1\"), 0)

The value i

6条回答
  •  时光说笑
    2021-01-13 04:36

    Bottom line:

    • use WorksheetFunction.Match(CDbl(date), range, 0)

    • Alternatively, use a Date cell's Value2 property (which will also be a Double) instead of Value for the search key.

    CLng suggested in other answers would discard the time part of the date.

    The same problem exists for the Currency data type but you can't use CDbl for it (see below for options).


    Range.Value2 Property (Excel) article suggests that Date and Currency types are "special" in that they have an "internal representation" that's in stark contrast with displayed value. Indeed:

    • Date is internally represented as IEEE 64-bit (8-byte) floating-point numbers where the integer part is the date and fractional part is the time
    • Currency is also 8-byte but is treated as a fixed-point number with 4 fractional digits (an integer scaled by 10'000)

    Apparently, Match compares these internal values for performance reasons. So, we must ensure that they, rather than the readable representations, match exactly.

    Since Date is already floating-point internally, CDbl(date) doesn't actually change the data.

    For the Currency type, CDbl does change data, so it's out of question. So either

    • use the exact representation of the key (to 4 fractional digits) this way or another if you require exact match, or
    • make the cells in the range actually be formulas with Round) if the value to compare with comes from elsewhere and/or you only require equality to 2 fractional digits

提交回复
热议问题