.find在一个程序中为我工作但不在另一个程序中工作

时间:2015-06-23 20:51:27

标签: excel vba excel-vba

您好,我有以下代码。实质上,它在每个工作表中抓取特定范围的唯一值,并将其添加到同一工作表一侧的范围内。

.find方法对我不起作用,就像在另一个程序中一样,我想解释为什么或我做错了什么或者在编写不同的代码时行为之间的区别。有意义吗?

    sub methodtwo()

    Dim cell As Range
    Dim strDATE As String
    Dim datehr As Range


    For i = 1 To Sheets.Count - 4
        Sheets(i).Activate
        Set datehr = Sheets(i).Range("H2", Sheets(i).Range("H2").End(xlDown))
                For Each cell In datehr
                        strDATE = cell.Value
                        Set cell = Sheets(i).Range("L1:L400").Find(What:=strName)

                            If cell Is Nothing Then
                                Sheets(i).Range("L1").End(xlDown).Offset(1, 0).Value = cell

                            End If

                Next cell
        Next i

    End Sub

下面是我之前编写的代码和编写上述代码的参考。在下面的代码中,find方法工作正常,并为指定范围添加了唯一值...上面的代码没有。

Sub methodone()

Dim sh As Worksheet
Dim r As Long
Dim a As Range
Dim al As Range
Dim strName As String

For Each sh In Worksheets
    sh.Activate
    sh.Range("K1").Activate
    Set al = ActiveSheet.Range("A2:A13000")

        For Each a In al
                strName = a.Value
                Set Cell = ActiveSheet.Range("K1:K400").Find(What:=strName)

                    If Cell Is Nothing Then
                        ActiveSheet.Range("K1").End(xlDown).Offset(1, 0).Value = a

                    End If

        Next a

Next sh


End Sub

我希望methodtwo()与methodone()完全相同,除了最后4张。

问题是否明显?我正在注意细节......尤其是在使用以前编写的代码时。

1 个答案:

答案 0 :(得分:0)

for methodone()我只需将strNAME更改为strDATE,这是将一个过程转换为另一个过程时的详细错误。我也改变了" cell"在IF语句之后转换为" strDATE"

    sub methodtwo()

    Dim cell As Range
    Dim strDATE As String
    Dim datehr As Range


    For i = 1 To Sheets.Count - 4
        Sheets(i).Activate
        Set datehr = Sheets(i).Range("H2", Sheets(i).Range("H2").End(xlDown))
                For Each cell In datehr
                        strDATE = cell.Value
                        Set cell = Sheets(i).Range("L1:L400").Find(What:=strDATE)

                            If cell Is Nothing Then
                                Sheets(i).Range("L1").End(xlDown).Offset(1, 0).Value = strDATE

                            End If

                Next cell
        Next i
     end sub