Excel- VBA - 将VLookup与Do While和IF功能合并

时间:2017-09-05 06:59:50

标签: excel vba excel-vba

我是excel VBA的新手,虽然我发现它对我的工作有帮助,但我目前仍然坚持使用vlookup,Do While Loop和IF功能。基本上我正在尝试编写一个宏,用户输入两个工作表的名称。从这里我希望宏在工作表1中取值“A2”,如果在工作表2的范围内找到它(3列宽度可变长度(即每周长度不同)返回“是”如果没有返回“否”。我希望这继续下去,直到工作表1的A列中的单元格不包含任何值。我继续得到运行时错误1004.我提出的代码如下:

Sub CheckWorksheets()

Dim NewName As String
Dim NewName2 As String

NewName = InputBox("Name me?")

'Here I ask the user to input the name of the first spreadsheet (worksheet 1)

ActiveSheet.Name = NewName
If ActiveSheet.Index = Worksheets.Count Then
    Worksheets(1).Select
Else
    ActiveSheet.Next.Select
End If

'Here I toggle between the first and second worksheet

NewName2 = InputBox("Name me?")
ActiveSheet.Name = NewName2

'Here I ask the user to input the name of the second spreadsheet (worksheet 2)

ActiveWorkbook.Worksheets(NewName).Activate
Range("A1").Offset(1, 3).Select

'Here I have selected the cell where I would like the output of the below formula to be input

Do While Not IsEmpty(ActiveCell.Offset(0, -1))
    If ActiveCell.Offset(0, 3) = Application.WorksheetFunction.VLookup(ActiveCell.Offset(0, 3), ActiveWorkbook.Worksheets(NewName2).Range(("A2"), Range("A2").End(xlDown)), 1, False) Then

        'Run time error 1004 pops up as soon as this line of code has been run
        ActiveCell.Value = "Yes"
        ActiveCell.Offset(1, 0).Select
    Else
        ActiveCell.Value = "No"
        ActiveCell.Offset(1, 0).Select
    End If
Loop
End Sub

我尝试过来自在线资源的多种变体,但似乎无法让它发挥作用。任何帮助和解释我出错的地方将不胜感激。 谢谢你的帮助!

编辑:有关我希望解决的问题的示例,请参阅Worksheet1Worksheet2(这是我要解决的问题的基本示例,我希望将其应用于其他问题)

0 个答案:

没有答案