gpt4 book ai didi

VBA EXCEL 范围语法

转载 作者:行者123 更新时间:2023-12-04 21:37:44 27 4
gpt4 key购买 nike

我不明白范围的语法。

为什么会这样:

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:A 是什么意思?为什么我不能使用
Range("A" & lastRow), 0

最佳答案

您的语法没有问题,您的代码应该可以正常工作。
使用 Match 等工作表函数的问题, Vlookup和其他查找功能是,如果没有找到正在搜索的值,它会抛出一个错误。

在您的情况下,您试图在一个单元格中搜索多个值。
所以让我们说你的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) ,它肯定会起作用,因为您正在尝试将所述范围的每个元素与其自身匹配,并且肯定会找到匹配项。

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") .
重要的是您处理错误以防您找不到匹配项。
一种方法是使用 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 .所以你可以在 Variant 中分配它的值变量并稍后在代码中使用它,没有任何问题。更好的是,使用 IsError测试以检查是否在上面的注释行中找不到值。

在上述两种情况下,我都使用了 Variant类型 num多变的。
主要原因是如果找不到匹配项,它会处理任何其他值。

至于范围语法,不要混淆,它相当简单。
请引用以下示例。
  • 单格 - 全部引用 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

    不要与使用单元格索引混淆。就像您从左到右,从上到下对所有单元格进行编号。
    enter image description here
    Cells(16385) ' refer to A2
  • 连续单元格范围 - 全部引用 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")
  • 非连续单元格 - 均指 A1、A3、A5、A7、A9
    Range("A1,A3,A5,A7,A9") ' Classic
  • 关于VBA EXCEL 范围语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405238/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com