如果在工作表中找到输入的单词,则执行A,如果未找到,则执行B.

时间:2016-01-15 23:16:43

标签: excel vba excel-vba

我试着写一个宏,如果我输入一个3个字母的月份缩写并且它在工作表中找到,A将被执行;否则(如果没有找到),然后弹出一个消息框(“你输入的内容与任何内容都不匹配”)。

以下是我的代码。当匹配时它很有效,但是当没有匹配或错误输入的3个字母的单词时,则会有一个调试消息 - " Run time error '91': Object variable or With block variable not set"

触发错误的行是:

 If Sheets("Sheet1").Cells.Find(what:=FindMonth, _
 LookIn:=xlFormulas, LookAt:=xlWhole).Column <> "0" Then

有人能说出它有什么问题吗?我该如何修复错误?谢谢。

Sub CDAEnter()
Dim RwcRow As Integer
Dim MSColumn1 As Integer
Dim MSColumn2 As Integer
Dim MSColumn3 As Integer
Dim MSColumn4 As Integer
Dim PDRRow1 As Integer
Dim PDRRow2 As Integer
Dim PDRRow3 As Integer
Dim PDRRow4 As Integer

Dim MColumn As Integer
Dim FindMonth As String

RwcRow = Sheets("Sheet2").Cells.Find(what:="RWC").Row

MSColumn1 = Sheets("Sheet2").Cells.Find(what:="ABC").Column

MSColumn2 = Sheets("Sheet2").Cells.Find(what:="DEF").Column

MSColumn3 = Sheets("Sheet2").Cells.Find(what:="GHI", LookIn:=xlValues, LookAt:=xlWhole).Column

MSColumn4 = Sheets("Sheet2").Cells.Find(what:="JKL").Column

PDRRow1 = Sheets("Sheet1").Cells.Find(what:="MNO").Row
PDRRow2 = Sheets("Sheet1").Cells.Find(what:="PQR").Row
PDRRow3 = Sheets("Sheet1").Cells.Find(what:="STU").Row
PDRRow4 = Sheets("Sheet1").Cells.Find(what:="VWX").Row

FindMonth = InputBox("Enter 3-letter Working Month ")

If Sheets("Sheet1").Cells.Find(what:=FindMonth, LookIn:=xlFormulas, LookAt:=xlWhole).Column <> "0" Then

MColumn = Sheets("Sheet1").Cells.Find(what:=FindMonth, LookIn:=xlFormulas, LookAt:=xlWhole).Column

Sheets("Sheet2").Cells(RwcRow, MSColumn1).Copy Destination:=Sheets("Sheet1").Cells(PDRRow1, MColumn)

Sheets("Sheet2").Cells(RwcRow, MSColumn2).Copy Destination:=Sheets("Sheet1").Cells(PDRRow2, MColumn)

Sheets("Sheet2").Cells(RwcRow, MSColumn3).Copy Destination:=Sheets("Sheet1").Cells(PDRRow3, MColumn)

Sheets("Sheet2").Cells(RwcRow, MSColumn4).Copy Destination:=Sheets("Sheet1").Cells(PDRRow4, MColumn)

Exit Sub

ElseIf IsError(MColumn) = True Then MsgBox "What you entered doesn't match anything"
Exit Sub
End If

End Sub

1 个答案:

答案 0 :(得分:0)

总结评论,我将其发布为答案(我知道你们可能太忙了,无法发布答案)。
如果他们中的任何一个决定发表他们的评论作为答案,那么我将删除我的。

首先声明一个变量:

Dim r As Range ' Find method returns a range object, so you'll need a variable to hold it

Set r = Sheets("Sheet1").Cells.Find(what:=FindMonth, _
        LookIn:=xlFormulas, LookAt:=xlWhole) 
        'I just copied above from your IF statement since you said it works

正如蒂姆所说,检查你是否找到了一些东西:

If Not r Is Nothing Then
    'You put the rest of your code here
Else
    MsgBox "What you entered doesn't match anything.", vbInformation
    'Inform the user through a message box
End If

如果您仍有问题,请在尝试中添加评论或修改您的问题 如果是完全不同的问题,请发布另一个。