gpt4 book ai didi

EXCEL VBA调试: Searching through the whole workbook

转载 作者:行者123 更新时间:2023-12-04 22:32:01 26 4
gpt4 key购买 nike

我正在为 Excel 中的数据库开发 VBA 宏。我有一个存储诸如姓名、电子邮件等信息的工作表(遗憾的是,这些信息并没有一致地放在所有工作表的同一列中,但电子邮件地址从“B:F”跨越),这个数据库被分成多个工作表。除了所有这些工作表之外,我还有另一个工作表(下面代码中的“Sheet2”),其中存储了分配给我的时事通讯的所有电子邮件地址。 (此表中的唯一信息是“A”列中的电子邮件地址)。

我正在处理的 VBA 应该遍历所有订阅时事通讯(“Sheet2”)的电子邮件地址,并检查它们是否存储在“数据库”中 - 以及其他工作表中。如果没有,请发出警告 - 在电子邮件旁边的单元格中写下“NOTFOUND”。

出于某种原因,VBA 在行上给了我一个运行时错误“对象不支持此属性或方法”:

使用工作表(sheetIndex).Range("B:F") .

本来我以为是因为我没有激活表格,但我仍然收到错误消息。

到目前为止我想出的代码:

Sub Search_for_emails()

Dim scanstring As String
Dim foundscan As Range
Dim lastRowIndex As Long
Dim ASheet As Worksheet

Set ASheet = Sheets("Sheet2")

lastRowInteger = ASheet.Range("A1", ASheet.Range("A1").End(xlDown)).Rows.Count

For rowNum = 1 To lastRowInteger
scanstring = Sheets("Sheet2").Cells(rowNum, 1).Value
For sheetIndex = 1 To ThisWorkbook.Sheets.Count
Sheets(sheetIndex).Activate
If Sheets(sheetIndex).Name <> "Sheet2" Then
With Sheets(sheetIndex).Range("B:F")
Set foundscan = .Find(What:=scanstring, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
End With
If foundscan Is Nothing Then
ASheet.Cells(rowNum, 2).Value = "NOTFOUND"

Else

' ASheet.Cells(rowNum, 2).Value = foundscan.Rows.Count

End If
End If
Next
Next rowNum

结束子

最佳答案

几点:

  • You should avoid Activate - 没必要。
  • 您应该始终限定诸如sheetrange , 否则 Excel 将使用事件工作簿/
    表,这并不总是你想要的。
  • Sheets 之间有区别和 Worksheets收藏。一个 Chart例如,-sheet 没有单元格,因此没有 Range .
  • 您正在声明一个变量 lastRowIndex但使用 lastRowInteger .为避免此类错误,请始终输入 Option Explicit在代码的顶部。

  • 将您的子更改为
    Sub Search_for_emails()

    Dim scanstring As String
    Dim foundscan As Range
    Dim lastRowIndex As Long, rowNum As Long
    Dim ASheet As Worksheet

    Set ASheet = ThisWorkbook.Worksheets("Sheet2")
    lastRowIndex = ASheet.Range("A1", ASheet.Range("A1").End(xlDown)).Rows.Count

    For rowNum = 1 To lastRowIndex
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
    If ws.Name <> "Sheet2" Then
    With ws.Range("B:F")
    Set foundscan = .Find(What:=scanstring, LookIn:=xlValues, LookAt:=xlWhole, _
    SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    End With
    If foundscan Is Nothing Then
    ASheet.Cells(rowNum, 2).Value = "NOTFOUND"
    Else
    ' ASheet.Cells(rowNum, 2).Value = foundscan.Rows.Count

    End If
    End If
    Next
    Next rowNum
    End Sub

    关于EXCEL VBA调试: Searching through the whole workbook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51944072/

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