我一直在将不同工作簿中的工作表添加到一个工作表中,但是,当我将代码复制并粘贴到新工作簿中的新模型中时,代码会继续向我显示错误,尽管它在旧工作簿中工作。 在下面的代码中,如何激活工作表“Question3”并让“设置myRange = question3.Range(”A3“)不会给我一个错误,就像我复制并粘贴到我的新工作簿之前一样。 谢谢。
Sub Main()
Dim gender As String
Call GetResponse(gender)
Call NameGenderRange(gender)
Call FormatOutputRange(gender)
Call EnterOutput(gender)
End Sub
Sub GetResponse(gender As String)
Dim response As Variant '<-- since the user can respond in alphabets or anything else
Dim ErrorCheck As Boolean
Do
response = InputBox("please enter 1 for boys, or 2 for girls") '<--prompting user for input
If IsNumeric(response) = False Then
ErrorCheck = True '<-- ensuring the input value is an integer
MsgBox ("Please enter a valid entry") '<-- ensuring user inputs only 1 or 2
ElseIf response = 1 Then '<-- if logic to differentiate between the gender averages
gender = "boys"
ElseIf response = 2 Then
gender = "girls"
Else
ErrorCheck = False
End If
Loop Until response = 1 Or response = 2 '<-- continously prompting the user to enter a correct value
End Sub
Sub NameGenderRange(gender As String)
Dim myRange As Range '<-- selecting the appropriate column to calculate the average
Dim question3 As Worksheet
If gender = "boys" Then
Set myRange = question3.Range("A3") '<-- selecting the column contaning data for boys
Else
Set myRange = question3.Range("B3") '<-- slecting the column contaning data for girls
End If
With myRange
Range(.Offset(1, 0), .End(xlDown)).Name = "average" '<--selecting the whole column and calling it "average"
End With
End Sub
Sub FormatOutputRange(gender As String)
With question3.Range("D9:E9") '<-- selecting the rows to display the "average"
With .Font
.Size = 12
.Underline = True '<-- altering the font
.Bold = True
.TintAndShade = 0
If gender = "boys" Then '<-- If logic to differentiate by colour
.ColorIndex = 5
Else
.ColorIndex = 3
End If
End With
End With
End Sub
Sub EnterOutput(gender As String)
question3.Range("D9").Value = "The average for " & gender & " is" '<-- naming the row to display the average
question3.Range("E9").Formula = "=Average(average)" '<-- displaying the average in cell E9
End Sub