Excel VBA - 使用Range.Find方法时出错

时间:2015-07-29 10:55:39

标签: excel vba

我正在VBA中构建一个程序,基本上,使用excel for VBA将文本粘贴到电子表格中。发生以下错误:

error on the xlvalues on this line: FoundCell = oSheet.Range("A:A").Find(What:=currentDay, LookIn:=xlvalues)

error is xlValues is not declared or may not be accessible due to its protection level

代码:

' Find Current Day In Excel Sheet
 Dim currentDay As String = String.Format(DateTime.Now.ToString("dd/MM/yyyy")) ' Todays Date In Format To Search Spreadsheet
Dim FoundCell As Excel.Range

FoundCell = oSheet.Range("A:A").Find(What:=currentDay, LookIn:=xlvalues)

If Not FoundCell Is Nothing Then
MsgBox(currentDay & " Found In Row: " & FoundCell.Row)
Else
MsgBox(currentDay & " Not Found In Sheet " & oSheet.Name)
End If

任何帮助都会得到很多批评,

谢谢, 肖恩

2 个答案:

答案 0 :(得分:1)

错误消息可能会产生误导,因为参数看起来没问题。 Range.Find方法返回范围对象,因此在VBA中,您必须使用Set关键字:

Set FoundCell = oSheet.Range("A:A").Find(What:=currentDay, LookIn:=xlvalues)

您可能很难找到日期,因为Excel会将它们存储为数字,然后将它们显示为日期。根据您的数据,您可能需要搜索格式化文本或使用Date变量。

如果您在VBA中写这个,这行不起作用:

Dim currentDay As String = String.Format(DateTime.Now.ToString("dd/MM/yyyy"))

您必须单独声明变量而不是初始化它们。

Dim currentDay As String
currentDay = Format(Date(),"dd/MM/yyyy")

答案 1 :(得分:0)

与ChipsLetten类似(但速度稍慢!),我将代码修改如下。

Sub notableopenfile()

    ' Find Current Day In Excel Sheet
    Dim currentDay As String
    'currentDay = Format(DateTime.Now.ToString("dd/MM/yyyy")) ' Todays Date In Format To Search Spreadsheet
    currentDay = Format(Now(), "dd/MM/yyyy")
    Dim FoundCell As Range

    Set FoundCell = ActiveSheet.Range("A:A").Find(What:=currentDay, LookIn:=xlValues) 'need 'set' here

    If Not FoundCell Is Nothing Then
        MsgBox (currentDay & " Found In Row: " & FoundCell.Row)
    Else
        MsgBox (currentDay & " Not Found In Sheet " & ActiveSheet.Name)
    End If

End Sub