你的错误基本上是你重用了 N,它是 sheet1 中的行数来定义 sheet2 上的范围。
所以我的建议是对变量使用更明确的名称来解释变量“包含”什么。
此外,如果您不使用隐式 Cells(xxx) 而是使用显式 Thisworkbook.Worksheets("Sheet1"),则可以省略工作表的选择(从而减少引用错误范围的错误的可能性)。
另外:您可以将 sheet1 的两列读入一个数组
Option Explicit
Public Sub updateSheet2IDs()
Dim wsSource As Worksheet
Set wsSource = ThisWorkbook.Worksheets("Sheet1")
Dim wsTarget As Worksheet
Set wsTarget = ThisWorkbook.Worksheets("Sheet2")
Dim cntRowsSheet1 As Long
Dim arrSource As Variant
With wsSource
cntRowsSheet1 = .Cells(.Rows.Count, "A").End(xlUp).Row
'array includes both columns: arrsource(1,1) = A2, arrsource(1,2) = B2
arrSource = .Range("A2:B" & cntRowsSheet1)
End With
Dim cntRowsSheet2 As Long, rgTarget As Range
With wsTarget
cntRowsSheet2 = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rgTarget = .Range("A2:A" & cntRowsSheet2)
Dim i As Long
For i = 1 To UBound(arrSource, 1) 'ubound gives you the upper bound of the array
rgTarget.Replace arrSource(i, 1), arrSource(i, 2)
Next
End With
End Sub
您可以通过使用currentregion 省略整个“cntRows” - 它返回一个单元格周围被空行和空列包围的区域(请参阅https://docs.microsoft.com/en-us/office/vba/api/excel.range.currentregion)。
这意味着 wsSource.Range("A1").CurrentRegion 将返回所有单元格,直到第一个空行和第一个空列 - 我认为这正是您正在寻找的。 sheet2 也一样。
要省略第一行,可以使用offset:
set rgTarget = wsTarget.Range("A1").CurrentRegion.Offset(1)
然后代码看起来像
Option Explicit
Public Sub updateSheet2IDs()
Dim wsSource As Worksheet
Set wsSource = ThisWorkbook.Worksheets("Sheet1")
Dim wsTarget As Worksheet
Set wsTarget = ThisWorkbook.Worksheets("Sheet2")
'array includes both columns: arrsource(1,1) = A2, arrsource(1,2) = B2
Dim arrSource As Variant
arrSource = wsSource.Range("A1").CurrentRegion.Offset(1)
Dim rgTarget As Range
Set rgTarget = wsTarget.Range("A1").CurrentRegion.Offset(1)
Dim i As Long
For i = 1 To UBound(arrSource, 1) 'ubound gives you the upper bound of the array
rgTarget.Replace arrSource(i, 1), arrSource(i, 2)
Next
End Sub