如何解决由单元格范围VBA

时间:2019-01-22 19:34:30

标签: excel vba

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

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

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

Sub MergeCells()

    Set Worksheet = Worksheets("Technical Data")

    With Worksheet
        For LIRCounter = 44 To 15 Step -1
            If .Cells(LIRCounter, 19).Value = Not IsEmpty(Cells(LIRCounter, 19)) Then
            Else
                .Range(.Cells(LIRCounter, 21), .Cells(LIRCounter, 26)).Merge
            End If

            If .Cells(LIRCounter, 19).Value = Not IsEmpty(Cells(LIRCounter, 19)) Then
            Else
                .Range(.Cells(LIRCounter, 21), .Cells(LIRCounter, 26)) = "N/A"
            End If
        Next LIRCounter

        For ETCounter = 44 To 15 Step -1
            If .Cells(ETCounter, 3).Value = "Structural" Then
                .Range(.Cells(ETCounter, 4), .Cells(ETCounter, 12)).Merge
            End If

            If .Cells(ETCounter, 3).Value = "Structural" Then
                .Range(.Cells(ETCounter, 4), .Cells(ETCounter, 12)) = "N/A - Structural"
            End If
        Next ETCounter

        For ETCounter2 = 44 To 15 Step -1
            If .Cells(ETCounter2, 3).Value = "Structural" Then
                .Range(.Cells(ETCounter2, 15), .Cells(ETCounter2, 26)).Merge
            End If

            If .Cells(ETCounter2, 3).Value = "Structural" Then
                .Range(.Cells(ETCounter2, 15), .Cells(ETCounter2, 26)) = "N/A - Structural"
            End If
        Next ETCounter2
    End With
End Sub

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

How it is supposed to work

1 个答案:

答案 0 :(得分:0)

建议您可以简化代码,删除大量多余的代码。因为三个循环都相同,所以只有一个for loop,而只有两个if else。为什么会出错?这对我来说是不可复制的。尝试注释掉大部分代码,并尝试缩小错误源。错误的来源也可能是工作表中的数据,因此请尝试首先在空白/虚拟工作表中运行代码。 HTH。

Option Explicit

Sub MergeCells()
    Dim TechnicalDataSheet As Worksheet
    Dim counter As Long

    Set TechnicalDataSheet = Worksheets("Technical Data")

    With TechnicalDataSheet 
        For counter = 44 To 15 Step -1
            If .Cells(counter, 19).Value = "" Then
                .Range(.Cells(counter, 21), .Cells(counter, 26)).Merge
                .Range(.Cells(counter, 21), .Cells(counter, 26)) = "N/A"
            End If

            If .Cells(counter, 3).Value = "Structural" Then
                .Range(.Cells(counter, 4), .Cells(counter, 12)).Merge
                .Range(.Cells(counter, 4), .Cells(counter, 12)) = "N/A - Structural"
                .Range(.Cells(counter, 15), .Cells(counter, 26)).Merge
                .Range(.Cells(counter, 15), .Cells(counter, 26)) = "N/A - Structural"
            End If
        Next counter
    End With
End Sub