【问题标题】:Match a value in VBA based on a condition根据条件匹配 VBA 中的值
【发布时间】:2016-11-28 10:15:29
【问题描述】:

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

它将运行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 运行时,它不会返回任何语法错误。任何人都可以帮助我吗?

谢谢!

【问题讨论】:

  • 你在哪里设置sh1?比如Set sh1 = Worksheets("Sheets1"),还有Dim startRow as String字符串 ! ???稍后循环遍历行,它需要是一个数字,IntegerLong
  • 而不是set sh1,我只能指Sheets(1)。操作,您对 startRow 是正确的。我会改正的

标签: vba match worksheet-function


【解决方案1】:

如果我没记错的话,你只需要多一行。在使用 WorkSheet 对象之前,您必须设置工作表。 (尽管对于这样一个简单的循环,您不需要所有这些对象)但是,要回答您的问题,请参见此处的第一行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多