2016-11-28 57 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") 
    '...