Vba 两个工作簿中的动态范围
我试图将主工作表中的一列与通过请求框打开的工作表中的一列进行比较。我想范围是动态的比较,我目前在代码中。在主表中,我希望它能看到a列,从单元格A2开始,进入最后一个条目,在打开的表中,它能看到E列,从单元格C2开始,进入最后一个条目。我目前使用的代码如下:Vba 两个工作簿中的动态范围,vba,excel,Vba,Excel,我试图将主工作表中的一列与通过请求框打开的工作表中的一列进行比较。我想范围是动态的比较,我目前在代码中。在主表中,我希望它能看到a列,从单元格A2开始,进入最后一个条目,在打开的表中,它能看到E列,从单元格C2开始,进入最后一个条目。我目前使用的代码如下: Sub InspectionCheck() Dim colI_Cell As Range Dim colI_Range As Range Dim rngLookupRange As Range Dim rngFound As Ran
Sub InspectionCheck()
Dim colI_Cell As Range
Dim colI_Range As Range
Dim rngLookupRange As Range
Dim rngFound As Range
Dim rngInspected As Range
Dim FileName As Variant
Dim wb As Workbook
Set colI_Range = ActiveSheet.Range("A2:A350").Cells
FileName = Application.GetOpenFilename(filefilter:="Excel Files(*.xlsx),*.xlsx")
Set wb = Workbooks.Open(FileName)
Set rngLookupRange = wb.Worksheets("owssvr").Range("E2:E350")
ThisWorkbook.Activate
For Each colI_Cell In colI_Range
With rngLookupRange
Set rngFound = .Find(What:=colI_Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not rngFound Is Nothing Then
colI_Cell.Offset(0, 1) = "Yes"
Else: colI_Cell.Offset(0, 1) = "No"
End If
End With
Next
Set rngLookupRange = Nothing
wb.Close False
Set wb = Nothing
Set colI_Range = Nothing
End Sub
如果您使用以下模块代码查找非空的最后一行,则很容易做到这一点:
Function FindLastRowNotBlank(ByRef ws As Worksheet, ByRef firstRow As Long, _
ByRef column As Long) As Long
Dim lastRow As Long
lastRow = firstRow
If ws.Cells(lastRow, column).Value <> "" Then
Do While ws.Cells(lastRow, column).Value <> ""
lastRow = lastRow + 1
Loop
FindLastRowNotBlank = lastRow - 1 'the last entry is the blank row so needs to subtract 1 from the result
Else
FindLastRowNotBlank = 0 'Returns 0 if the firstRow is empty
Exit Function
End If
End Function
让我知道它是如何工作的。谢谢
Clint您的代码有什么问题?你在哪里卡住了?你能详细说明一下吗?
Sub InspectionCheck()
Dim colI_Cell As Range
Dim colI_Range As Range
Dim rngLookupRange As Range
Dim rngFound As Range
Dim rngInspected As Range
Dim FileName As Variant
Dim wb As Workbook
Dim i as Long, rngStr as String
i = FindLastRowNotBlank(ActiveSheet, 2,1) 'I have added this
rngStr = "A2:A" & i 'I have added this
Set colI_Range = ActiveSheet.Range(rngStr).Cells 'I have modified this
FileName = Application.GetOpenFilename(filefilter:="Excel Files(*.xlsx),*.xlsx")
Set wb = Workbooks.Open(FileName)
i = FindLastRowNotBlank(wb.Worksheets("yoursheetnamehere"), 2,5) 'I have added this you need to fill in the worksheet name
rngStr = "E2:E" & i 'I have added this
Set rngLookupRange = wb.Worksheets("owssvr").Range(rngStr) ' I have modified this
ThisWorkbook.Activate
For Each colI_Cell In colI_Range
With rngLookupRange
Set rngFound = .Find(What:=colI_Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not rngFound Is Nothing Then
colI_Cell.Offset(0, 1) = "Yes"
Else: colI_Cell.Offset(0, 1) = "No"
End If
End With
Next
Set rngLookupRange = Nothing
wb.Close False
Set wb = Nothing
Set colI_Range = Nothing
End Sub