为动态行的目标搜索创建VBA代码

时间:2019-07-08 14:32:42

标签: excel vba

宏按钮位于Excel工作簿的其他选项卡中。

我想为保险计划创建综合费率。我需要更改数据第一行("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9)中的值,以使下面四行("G" & EElastrow + 13 & ":" & lastcolumnletter & EElastrow + 13)中的值等于零。这些行需要动态,因为它们会根据客户端的大小而变化。

当我运行此宏时,它总是说“ Range类的选择方法失败”。我的假设是我无法“选择”所需的列。如何在不使用ActiveSheet的情况下选择这些列?

这个范围在我的Excel工作簿的几乎所有其他部分都可以正常工作,但不适用于此应用程序。

我做错了什么?

我已更改为ActiveSheets,但这也修改了同时找到宏按钮的选项卡。我无法将宏按钮移至包含最终结果的标签。

' Perform Goal Seek
Dim i As Integer, numCols As Integer
Dim cCell As String ' Changing range of cells
Dim sCell As String ' Changing range of cells
Dim lastColumnNum As Integer, EElastrow As Integer
Dim lastcolumnletter As String

    EElastrow = 5 + Worksheets("Master census").Range("h5") - 1
    lastColumnNum = Sheets("Carrier rates by EE").Cells(5, Columns.Count).End(xlToLeft).column
    lastcolumnletter = Split(Columns(lastColumnNum).Address(), "$")(2)

' Disable Excel Properties
With Application
    .ScreenUpdating = False ' Prevent screen flickering
    .DisplayAlerts = False ' Turn off Alerts
    .EnableEvents = False ' Prevent all events
End With

' Run the Goal Seek on multiple columns
' Select the range of cells for the Goal Seek to change
Worksheets("Carrier rates by EE").Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9).Select
Worksheets("Carrier rates by EE").Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9).Value = Worksheets("Carrier rates by EE").Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9).Value
numCols = Selection.Columns.Count

' Move across the cells in Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9)
For i = 0 To numCols - 1
    cCell = Worksheets("Carrier rates by EE").Cell.Offset(0, i).Address ' range of cells to change
    sCell = Worksheets("Carrier rates by EE").Cell.Offset(4, i).Address ' 4 rows down from Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9) = Range("G" & EElastrow + 9 & ":" & lastcolumnletter & EElastrow + 9)

    ' Runs the multi column Goal Seek
    Worksheets("Carrier rates by EE").Range(sCell).Goalseek Goal:=0, ChangingCell:=Worksheets("Carrier rates by EE").Range(cCell)
Next i

' Enable Excel Properties
With Application
    .ScreenUpdating = True ' Enable screen flickering
    .DisplayAlerts = True ' Turn on Alerts
    .EnableEvents = True ' Re-enable all events
End With

我应该看到此应用程序仅应用于选项卡“ EE的运营商费率”。我对此代码的引用来自以下youtube视频: https://www.youtube.com/watch?v=NsYvERSCAfU

谢谢大家帮助我更好地传达了需要的信息。

0 个答案:

没有答案