2016-11-28 134 views
0

在工作表2中,我想要一个宏运行表值,主要在列F(最大入口浓度)和列B(操作)中,如下图所示Worksheet 1。基本上,它会找到对应于列F的0值的参考操作。根据条件在VBA中匹配值

它将运行列F,并且当找到0值时,它会返回匹配操作。这样做直到表的结尾。如果我有1A - 0,2B - 0和4C - 0,它将始终选择宏查找0值的第一个操作。在图片中,宏必须返回值1,这是第一个操作。

所以我写了下面的代码,并给出了运行时错误'91':对象变量或块变量未设置。

Dim sh1 As Worksheet 
Dim StartCellCin As Range 
Dim StartCellO As Range 
Dim startRow As String 
Dim multiplication As Integer 
Dim countRows As Integer 
Dim lastRow As Long 
Dim operation As Long 

Set StartCellCin = sh1.Range("F13") 
Set StartCellO = sh1.Range("B13") 
startRow = StartCellCin.Row 
multiplication = sh1.Range("D4").Value2 * sh1.Range("D6").Value2 
countRows = multiplication - 1 
lastRow = startRow + countRows 

Do While startRow < lastRow 
If StartCellCin.Value = 0 Then 
    operation = Application.WorksheetFunction.Index(sh1.Range("B13"), Application.WorksheetFunction.Match(0, sh1.Range("startRow:lastRow"),0),1) 
    startRow = startRow + 1 
Else 
    startRow = startRow + 1 
    If StartCellCin.Offset(startRow).Value = 0 Then 
    operation = Application.WorksheetFunction.Index(sh1.Range("B13").Offset(startRow), Application.WorksheetFunction.Match(0,sh1.Range("startRow:lastRow"),0),1) 
    startRow = startRow + 1 
    End If 
End If 
Loop 

当我使用Option Explicit运行时,它不返回任何语法错误。任何人都可以帮助我?

谢谢!

+1

你在哪里设置'sh1'?像'Set sh1 = Worksheets(“Sheets1”)',还有'Dim startRow as String'? **字符串**! ????循环遍历行后它需要是一个数字,或者是'Integer'或者'Long' –

+0

而不是设置sh1,我只能引用Sheets(1)。行动,你是对的startRow。我会纠正它 – vbalearner

回答

0

如果我没有错,你只需要一条线。您必须在使用工作表对象之前设置工作表。 (虽然你不需要这么简单的循环就可以得到所有这些对象)但是,要回答你的问题,请看这里的第一行:

Set sh1 = Sheets("Your Sheet's Name") 
    Set StartCellCin = sh1.Range("F13") 
    Set StartCellO = sh1.Range("B13") 
    '...