如何基于多个行的单元格值合并跨单元格

时间:2019-01-22 17:24:23

标签: excel vba

每次我尝试运行宏时,被LIRCounter包围的第一部分都运行良好,但是Excel返回“运行时错误'1004':应用程序定义或对象定义的错误”,并且Debug突出显示了我的宏。 Range(...)。合并宏的其余部分。

我尝试通过删除.Merge,Counter变量并重写我的整个代码来重新格式化范围,但是我无法缩小范围的哪一部分会导致错误。

Sub MergeCells()

    Dim FirstRow As Long
    Dim LastRow As Long
    Dim TechnicalDataSheet As Worksheet
    Dim LIRCounter As Long
    Dim ETCounter As Long
    Dim ETCounter2 As Long

    FirstRow = 15
    LastRow = 44

    Set TechnicalDataSheet = Worksheets("Technical Data")

    With TechnicalDataSheet
        For LIRCounter = FirstRow To LastRow
            If Cells(LIRCounter, 19).Value = Not IsEmpty(Cells(LIRCounter, 19)) Then
            Else
                Range("U" & LIRCounter, "Z" & LIRCounter).Merge
            End If
            If Cells(LIRCounter, 19).Value = Not IsEmpty(Cells(LIRCounter, 19)) Then
            Else
                Range("U" & LIRCounter, "Z" & LIRCounter) = "N/A"
            End If
        Next LIRCounter

        For ETCounter = FirstRow To LastRow
            If Cells(ETCounter, 3).Value = "Structural" Then
                Range("D" & ETCounter, "L" & ETCounter).Merge
            End If
            If Cells(ETCounter, 3).Value = "Structural" Then
                Range("D" & ETCounter, "L" & ETCounter) = "N/A - Structural"
            End If
        Next ETCounter

        For ETCounter2 = FirstRow To LastRow
            If Cells(ETCounter2, 3).Value = "Structural" Then
                Range("O" & ETCounter2, "Z" & ETCounter2).Merge
            End If
            If Cells(ETCounter2, 3).Value = "Structural" Then
                Range("O" & ETCounter2, "Z" & ETCounter2) = "N/A - Structural"
            End If
        Next ETCounter2
    End With
End Sub

预期结果是,如果从单元格C15的下拉菜单中选择“结构”,则单元格D15:L15合并为一个单元格,而单元格O15:Z15合并为一个单元格。直到第44行的每一行都一样。运行宏时,它仅返回“运行时错误'1004':应用程序定义的错误或对象定义的错误”,并且没有单元格被合并。

1 个答案:

答案 0 :(得分:0)

您已经编写了“ With TechnicalDataSheet”,但是下面的行是指单元格而不是.Cells 因此选择活动表而不是您想要的目标。在所有“单元格”引用之前添加句号