根据各种单元格内容组合设置字符串值“ myTerm”

时间:2018-11-22 13:04:17

标签: excel vba if-statement

是否可以使用一系列myTerm语句设置If的值?

我在工作表中有3列,这些列将在一年中添加数据。

我有以下几种情况:

K有数据,M&O =“秋天”
K和M有数据,O为空=“ Spring”
K,M和O都有数据= Summer

我写了以下代码(完整代码的片段):

Sub FilterProgressData()

    Dim myTerm As String

    If SrcWs.Cells(i, "O").Value = "" And SrcWs.Cells(i, "M").Value = "" And _
        SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Autumn"

    ElseIf SrcWs.Cells(i, "O").Value = "" And SrcWs.Cells(i, "M").Value <> "" _
        And SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Spring"

    ElseIf SrcWs.Cells(i, "O").Value <> "" And SrcWs.Cells(i, "M").Value <> "" _
        And SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Summer"

但收到“运行时错误'1004'错误-应用程序定义或对象定义的错误'

任何建议将不胜感激!

谢谢。

2 个答案:

答案 0 :(得分:0)

这很好。我的if语句没有问题。

Option Explicit

Sub FilterProgressData()
Dim myTerm As String
Dim i As Integer
Dim SrcWs As Worksheet
Set SrcWs = Worksheets("Sheet1")

i = 1

    If SrcWs.Cells(i, "O").Value = "" And SrcWs.Cells(i, "M").Value = "" And _
        SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Autumn"

    ElseIf SrcWs.Cells(i, "O").Value = "" And SrcWs.Cells(i, "M").Value <> "" _
        And SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Spring"

    ElseIf SrcWs.Cells(i, "O").Value <> "" And SrcWs.Cells(i, "M").Value <> "" _
        And SrcWs.Cells(i, "K").Value <> "" Then
            myTerm = "Summer"

    End If
    End Sub

答案 1 :(得分:0)

我可以在您的摘要中看到的问题:

  • SrcWs未在代码段的任何地方声明/实例化。
  • i未分配。如果将其隐式转换为0(使用Cells()时),则您正在尝试访问工作表的第0行(该行不存在,将给您带来错误)。

假设您要基于K,M,O列和第1至100行的值(例如)为myTerm分配一个值。然后,您可以尝试以下操作:

Option Explicit

Sub ConditionallyAssignMyTerm()
    Dim SrcWs As Worksheet
    Set SrcWs = ThisWorkbook.Worksheets("Sheet1")

    Dim i As Long ' Might be better to rename this to rowIndex or something more descriptive than just i

    With SrcWs
        Dim myTerm As String

        Dim columnKisBlank As Boolean
        Dim columnMisBlank As Boolean
        Dim columnOisBlank As Boolean

        For i = 1 To 100 ' Arbitrary loop values
            columnKisBlank = CellIsBlank(.Cells(i, "K"))
            columnMisBlank = CellIsBlank(.Cells(i, "M"))
            columnOisBlank = CellIsBlank(.Cells(i, "O"))

            If (Not columnKisBlank) And columnMisBlank And columnOisBlank Then
                myTerm = "Autumn"

            ElseIf (Not columnKisBlank) And (Not columnMisBlank) And columnOisBlank Then
                myTerm = "Spring"

            ElseIf (Not columnKisBlank) And (Not columnMisBlank) And (Not columnOisBlank) Then
                myTerm = "Summer"
            End If
        Next i

    End With
End Sub

Function CellIsBlank(ByRef cellToCheck As Range) As Boolean
    CellIsBlank = VBA.IsEmpty(cellToCheck.Value2) Or (Len(cellToCheck.Value2) = 0)
End Function