与vba脱节,所以我确定它在某处是一个愚蠢的错误。如果有人能指出这一点,将会非常有用
代码:
Private Function generate() As Integer
Dim source_size As Long
Dim target_size As Long
Dim i As Long
Dim j As Long
Dim count As Long
Dim source1 As Range
Dim target1 As Range
Set source1 = Worksheets("Filter").Range(C4, C6498)
Set target1 = Worksheets("30").Range(A2, AP95787)
source_size = source1.Height
target_size = target1.Height
For i = 1 To source_size Step 1
For j = 1 To target_size Step 1
If Application.source1.Cells(i, 1).Value = target1.Cells(j, 5).Value Then
target1.Row(j).Select
'Selection.Copy
Worksheet("result").Range("A1").Rows("1:1").Insert Shift:=xlDown
End If
Next j
Next i
generate = 0
End Function
答案 0 :(得分:3)
首先你有一个声明你的范围的问题,C4
在VBA中被认为是一个变量,你需要使用它们:
[C4]
或Range("C4")
或Cells(4,3)
或Cells(4,"C")
因此,您的行或定义范围应如下所示:
Set source1 = Worksheets("Filter").Range([C4], [C6498])
Set target1 = Worksheets("30").Range(Range("A2"), Range("AP95787"))
其次,.Height
属性会为您提供范围的大小,而不是行数,以获取行数,您需要使用Range(...).Rows.Count
source_size = source1.Rows.count
target_size = target1.Rows.count
以下是您的完整代码:
Option Explicit
Public Function generate() As Integer
Dim source_size As Long
Dim target_size As Long
Dim i As Long
Dim j As Long
Dim count As Long
Dim source1 As Range
Dim target1 As Range
Set source1 = Worksheets("Filter").Range("C4:C6498")
Set target1 = Worksheets("30").Range("A2:AP95787")
source_size = source1.Rows.count
target_size = target1.Rows.count
For i = 1 To source_size Step 1
For j = 1 To target_size Step 1
If Application.source1.Cells(i, 1).Value = target1.Cells(j, 5).Value Then
target1.Rows(j).Select
'Selection.Copy
Worksheets("result").Range("A1").Rows("1:1").Insert Shift:=xlDown
End If
Next j
Next i
generate = 0
End Function