我是Excel VBA的新手。我正在尝试使用我在网上找到的VBA功能,使用户能够一次在多个单元格上使用goalseek。如何在电子表格中调用该函数,以及如何指向应该与函数中的变量关联的单元格(例如Taddr,Aaddr,gval)。我是否必须在代码本身中编写单元格值和范围,然后以这种方式运行它?
也许我应该重新定义函数,以便它将这些变量作为输入,所以我可以写一个像= GSeekA(Taddr,Aaddr,gval)的公式
Option Explicit
Sub GSeekA()
Dim ARange As Range, TRange As Range, Aaddr As String, Taddr As String, NumEq As Long, i As Long, j As Long
Dim TSheet As String, ASheet As String, NumRows As Long, NumCols As Long
Dim GVal As Double, Acell As Range, TCell As Range, Orient As String
' Create the following names in the back-solver worksheet:
' Taddr - Cell with the address of the target range
' Aaddr - Cell with the address of the range to be adjusted
' gval - the "goal" value
' To reference ranges on different sheets also add:
' TSheet - Cell with the sheet name of the target range
' ASheet - Cell with the sheet name of the range to be adjusted
Aaddr = Range("aaddr").Value
Taddr = Range("taddr").Value
On Error GoTo NoSheetNames
ASheet = Range("asheet").Value
TSheet = Range("tsheet").Value
NoSheetNames:
On Error GoTo ExitSub
If ASheet = Empty Or TSheet = Empty Then
Set ARange = Range(Aaddr)
Set TRange = Range(Taddr)
Else
Set ARange = Worksheets(ASheet).Range(Aaddr)
Set TRange = Worksheets(TSheet).Range(Taddr)
End If
NumRows = ARange.Rows.Count
NumCols = ARange.Columns.Count
GVal = Range("gval").Value
For j = 1 To NumCols
For i = 1 To NumRows
TRange.Cells(i, j).GoalSeek Goal:=GVal, ChangingCell:=ARange.Cells(i, j)
Next i
Next j
ExitSub:
End Sub
答案 0 :(得分:1)
GSeekA是一个Subprocedure,而不是一个函数。无法从函数可以从工作表单元格中调用子过程。并且您不希望将GSeekA转换为函数。函数应该用于将值返回到调用它们的单元格。他们不应该(通常也不会)改变工作表上的其他东西。
您需要将GSeekA作为子程序运行。现在问题变成了如何将用户提供的信息提供给子。您可以使用InputBox提示用户输入一条信息。如果你有太多,InputBox会变得很麻烦。
您可以在电子表格中创建用户必须输入信息的区域,然后从该区域中读取。这就是它现在的设置方式。它正在读取名为asheet和tsheet的单元格。只要存在这些命名范围,代码就可以工作。
最后,您可以创建用户将填写的UserForm。这就像把一堆InputBox放在一个表单上。
更新这是一个简单的程序,您可以从这里开始并加强。
Public Sub GSeekA()
Dim rAdjust As Range
Dim rTarget As Range
Dim dGoal As Double
Dim i As Long
'Set these three lines to what you want
Set rAdjust = Sheet1.Range("I2:I322")
Set rTarget = Sheet1.Range("J2:J322")
dGoal = 12.1
For i = 1 To rAdjust.Count
rTarget.Cells(i).GoalSeek dGoal, rAdjust.Cells(i)
Next i
End Sub