Excel VBA – 错误使用Range.Find方法
我正在VBA中build立一个程序,基本上,使用VBA的excel将文本粘贴到电子表格中。 以下错误已经说明会发生:
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
任何帮助将是非常appricated,
谢谢,肖恩
错误信息可能会引起误解,因为您的参数看起来不错。 Range.Find
方法返回一个范围对象,所以在VBA中你必须使用Set
关键字:
Set FoundCell = oSheet.Range("A:A").Find(What:=currentDay, LookIn:=xlvalues)
您可能很难finddate,因为Excel将它们存储为数字,然后将它们显示为date。 根据您的数据,您可能需要search带格式的文本或使用Date
variables。
如果您在VBA中编写此代码,则此行不起作用:
Dim currentDay As String = String.Format(DateTime.Now.ToString("dd/MM/yyyy"))
您必须分别声明variables来初始化它们。
Dim currentDay As String currentDay = Format(Date(),"dd/MM/yyyy")
与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