VBA EXCEL范围语法

我不明白范围的语法。

为什么这个工作:

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

但是这不起作用:

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

为什么我需要使用

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

什么A1:一个意思? 为什么我不能使用

 Range("A" & lastRow), 0 

你的语法没有错,你的代码应该工作得很好。
使用工作表函数如MatchVlookup和其他查找函数的问题是,如果找不到的值被查找,则会引发错误。

在你的情况下,你正试图在一个单元格中search多个值。
所以让我们说你的lastrow是9.你的代码将从Cell(2,1)循环到Cell(9,1)检查它是否在Range("A" & lastrow)Range("A9")

如果您从Cell(2,1)Cell(9,1)的值与Range("A9")值相同,则不会出现错误。

现在,如果你使用Range("A1:A" & lastrow) ,它肯定会起作用,因为你试图将上述范围的每个元素都与自己匹配,并且肯定会find一个匹配。

 WorksheetFunction.Match(Cells(2,1), Range("A1:A9")) 'will return 2 WorksheetFunction.Match(Cells(3,1), Range("A1:A9")) 'will return 3 ' ' 'And so on if all elements are unique 

使用Range("A9")Range("A1:A9")无关紧要。
重要的是,如果你没有find一个匹配,你处理错误。
一种方法是使用On Error Resume NextOn Error Goto 0像这样:

 Sub ject() Dim num As Variant Dim i As Long, lastrow As Long: lastrow = 9 For i = 2 To lastrow On Error Resume Next num = WorksheetFunction.Match(Cells(i, 1), Range("A" & lastrow), 0) If Err.Number <> 0 Then num = "Not Found" On Error GoTo 0 Debug.Print num Next End Sub 

另一种方法是使用Application.Match通过WorksheetFunction.Match像这样:

 Sub ject() Dim num As Variant Dim i As Long, lastrow As Long: lastrow = 9 For i = 2 To lastrow num = Application.Match(Cells(i, 1), Range("A" & lastrow), 0) Debug.Print num 'If Not IsError(num) Then Debug.Print num Else Debug.Print "Not Found" Next End Sub 

Application.Match以相同的方式工作,但返回#N/A时不会错误。 所以你可以把它的值赋给一个Variantvariables,稍后在代码中使用它,没有任何问题。 更好的是,使用IsErrortesting来检查在注释行中是否找不到如上所示的值。

在上述两种情况下,我使用了Varianttypes的numvariables。
主要的原因是如果找不到匹配的话,它可以处理任何其他的值。

至于范围语法,不要混淆,这是相当简单的。
参考下面的例子。

  1. 单细胞 – 全部参考A1

     Cells(1,1) ' Using Cell property where you indicate row and column Cells(1) ' Using cell property but using just the cell index Range("A1") ' Omits the optional [Cell2] argument 

    不要混淆使用单元格索引。 就像你从左到右,从上到下编号所有单元格一样。 在这里输入图像描述

     Cells(16385) ' refer to A2 
  2. 连续单元格的范围 – 全部参考A1:A10

     Range("A1:A10") ' Classic Range("A1", "A10") ' or below Range(Cells(1, 1), Cells(10, 1)) 

    上面使用相同的语法Range(Cell1,[Cell2])其中第一个省略了optional参数[Cell2] 。 正因为如此,下面也是有效的:

     Range("A1:A5","A6:A10") Range("A1", "A8:A10") Range("A1:A2", "A10") 
  3. 非连续单元格 – 全部参考A1,A3,A5,A7,A9

     Range("A1,A3,A5,A7,A9") ' Classic 

没有关于错误的任何具体细节,我认为Match不会返回您期望的值,而是#N / A错误。 匹配具有语法

=匹配(lookup_value,lookup_range,match_type)

lookup_range通常由几个单元格的范围组成,包括具有多行的列或具有多列的行。

在你的公式中,你只有一个单元格在lookup_range中。 假设拉斯特罗是10.循环的前三个运行产生公式

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

这是一个有效的公式,但在大多数情况下,结果不会是一个匹配,而是一个错误。 而你可能想要的是

 =Match(A2,A1:A10,0) 

再次查看你的代码,将它们拼接在一起,找出为什么需要A1:A作为公式中的string常量:

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