【发布时间】:2017-01-16 00:04:27
【问题描述】:
这个周末我开始使用宏(我倾向于快速上手计算机)。到目前为止,当我有问题时,我已经能够通过搜索答案来解决问题,但是我的理解是如此有限,以至于我已经到了不再理解答案的地步。我正在使用 VBA for Excel 编写一个函数。我希望该函数产生一个范围,然后可以稍后将其用作另一个函数的变量。这是我的代码:
Function StartingCell() As Range
Dim cNum As Integer
Dim R As Integer
Dim C As Variant
C = InputBox("Starting Column:")
R = InputBox("Starting Row:")
cNum = Range(C & 1).Column
Cells(R, cNum).Select
到目前为止的代码有效。它选择了单元格,一切都很好。
Set StartingCell = Range(Cell.Address)
End Function
我想我不知道如何将此位置保存为 StartingCell()。我使用了与“= Range(Cell.Address)”在另一个非常相似的情况下看到的相同的代码。但这在这里行不通。有任何想法吗?我需要提供更多信息以寻求帮助吗?感谢您的意见!
编辑:我忘记添加我正在使用 InputBox 来选择起始单元格,因为我将在多个数据集上重复使用此代码,并且需要将每个数据集放在不同的位置,每次都会遵循相同的人口模式。
谢谢 A.S.H 和 Shai Rado
我已将代码更新为:
Function selectQuadrant() As Range
Dim myRange As Range
Set myRange = Application.InputBox(Prompt:="Enter a range: ", Type:=8)
Set selectQuadrant = myRange
End Function
这运作良好。 (看起来文本应该显示“输入范围:”但它只显示输入框的“输入”。这可能是因为我在 Mac 上?
无论如何。我能够调用该函数并将其设置为我的其他代码中的一个新变量。但是我正在做类似设置 long (用于颜色)的操作,因此我可以在一个范围内选择某种颜色的单元格,但我在这里也遇到了各种对象错误。我真的不明白。 (而且我认为我正在处理更多问题,因为在 Mac 上,我没有典型的窗口来编辑我的宏。只有我,基本上是一个文本框和互联网。
所以。这也是颜色的函数和使用这些函数的子。 (我已经编辑了这么多,我不确定我从哪里开始或错误在哪里。)
我正在使用函数并将变量设置为等于函数结果。
Sub SelectQuadrantAndPlanets()
Dim quadrant As Range
Dim planetColor As Long
Set quadrant = selectQuadrant()
Set planetColor = selectPlanetColor() '<This is the row that highlights as an error
Call selectAllPlanets(quadrant, planetColor)
End Sub
这是我用来在我的范围内选择要突出显示的颜色的功能
我也可以使用我选择的范围内的内部颜色,但我不知道如何将内部颜色设置为变量,所以我在输入框中选择了 1、2 或 3。
Function selectPlanetColor() As Long
Dim Color As Integer
Color = InputBox("What Color" _
& vbNewLine & "1 = Large Planets" _
& vbNewLine & "2 = Medium Planets" _
& vbNewLine & "3 = Small Planets")
Dim LargePlanet As Long
Dim MediumPLanet As Long
Dim smallPlanet As Long
LargePlanet = 5475797
MediumPlanet = 9620956
smallPlanet = 12893591
If Color = 1 Then
selectPlanetColor = LargePlanet
Else
If Color = 2 Then
selectPlanetColor = MediumPlanet
Else
If Color = 3 Then
selectPlanetColor = smallPlanet
End If
End If
End If
End Function
任何帮助都会令人惊叹。我已经能够单独完成这些部分,但现在将它们全部合并到一个调用它们的子中对我来说效果不佳。感谢 VBA 社区 :)
【问题讨论】:
-
什么是
Cell.Address?你想使用那个选定的单元格吗?喜欢Set StartingCell = Cells(R, cNum).Address?或者,... = Range(Cells(R,cNum),Cells(R,cNum))?此外,最好在 VBA 中使用 avoid using.Select/.Activate。编辑:另外,我想你想要cNum = Range(C & ":1").Column假设C是一封信 -
老实说,我刚刚看到它(Cell.Address)在其他地方使用,并认为它可能做了我需要的事情。我是一个极端的新手(我从 2 天前开始)
-
@jessmariemetal 您测试过以下任何答案吗?有什么反馈吗?