3

VBA でこのサブルーチンを実行すると、奇妙なエラーが発生します。

Sub NameColumns()
' name key columns for later reference in formulas
Dim startdatecol As Integer

' name start date column
startdatecol = ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Column
End Sub

実行時エラー '91': オブジェクト変数または With 変数が設定されていません

このサブルーチン エラーを修正する方法について何かアイデアはありますか? そして、なぜそれが起こっているのですか?

ありがとう、アメ

4

1 に答える 1

5

問題はFind、セルが見つからないことです。

次のことが真であることがわかります (しゃれが意図されています)。

MsgBox ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) Is Nothing

最初にすべきことは、探しているセルが見つかるように検索を修正することです。

編集:

おそらく、問題をよりよく説明する変更は次のとおりです。

Dim found as Range
Dim startDateCol as Integer

Set found = ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

If Not found Is Nothing Then startDateCol = found.Column

MsgBox startDateCol 'This will be zero if the "Start Date" cell wasn't found.

コメントに応答するように編集します。

'This should find the exact text "Start Date" (case sensitive) in the header row.
'A cell containing, for example "The Start Date" will not be matched.
Set found = ActiveSheet.Range("1:1").Find("Start Date", LookIn:=xlValues, _
                                           LookAt:=xlWhole, MatchCase:=True)
于 2012-08-11T21:55:28.537 に答える