VBA EXCEL Range syntax

前端 未结 2 1899
有刺的猬
有刺的猬 2020-12-21 21:12

I don\'t understand syntax for range.

Why does this work:

For i = 1 To 10
    Range(\"A\" & i & \":D\" & i).Copy
Next

B

2条回答
  •  一生所求
    2020-12-21 21:43

    Without any specific details about the error, I assume that Match does not return the value you expect, but rather an #N/A error. Match has the syntax

    =match(lookup_value, lookup_range, match_type)

    The lookup_range typically consists of a range of several cells, either a column with several rows or a row with several columns.

    In your formula, you have only one cell in the lookup_range. Let's say Lastrow is 10. The first three runs of the loop produce the formula

    =Match(A2,A10,0)
    =Match(A3,A10,0)
    =Match(A4,A10,0)
    

    It is a valid formula but in most cases the result won't be a match but an error. Whereas what you probably want is

    =Match(A2,A1:A10,0)
    

    Looking again at your code, stitch it together and find why you need A1:A as a string constant in your formula:

    For i = 2 To lastRow
        num = WorksheetFunction.Match(Cells(i, 1), Range("A1:A" & lastRow), 0)
    Next
    

提交回复
热议问题