[英]Can I reference another cell in another sheet using variables?
Please forgive my absolute lack of knowledge, I normally program in Python and only dabbed my toe in VBA today for one specific purpose, I want to prepare one worksheet that will do the work I need.请原谅我绝对缺乏知识,我通常在 Python 中编程,而今天只在 VBA 中为一个特定目的轻拍我的脚趾,我想准备一张工作表来完成我需要的工作。
In my learning process, I've been trying to write small functions on which I would build my final product.在我的学习过程中,我一直在尝试编写用于构建最终产品的小函数。 I'm stuck on trying to successfully be able to pass a string/cell as a reference to specific cells in another sheet.我一直试图成功地将字符串/单元格作为对另一张表中特定单元格的引用进行传递。 Example: I have two sheets called Dog and Cat, and I have their weights in cells A1.示例:我有两张名为 Dog 和 Cat 的工作表,我将它们的权重放在单元格 A1 中。 I tried writing a function that would would fetch the Cat's weight while being in the Dog's sheet.我试着写一个 function 可以在狗的床单中获取猫的重量。 It goes something like this:它是这样的:
Function CatsWeight(ByVal species As String) As Double
Dim weight As Range
Set weight = Worksheets(species).Range("A1")
CatsWeight = weight.Value
End Function
It just returns #VALUE.它只返回#VALUE。 error: I also tried to switch it up and call the range as a variable:错误:我也尝试将其切换并将范围称为变量:
Function CatsWeight(ByVal cell As Range) As Double
Dim weight As Range
Set weight = Worksheets("Cat").cell
CatsWeight = weight.Value
End Function
Also doesn't work, but when I call both on "manually" it works:也不起作用,但是当我“手动”调用两者时,它可以工作:
Function CatsWeight() As Double
Dim weight As Range
Set weight = Worksheets("Cat").Range("A1")
CatsWeight = weight.Value
End Function
What am I doing wrong in my referencing?我在引用时做错了什么?
Edit because I forgot to say, I call on the functions like this:编辑因为我忘了说,我调用这样的函数:
=CatsWeight(Cat) =猫体重(猫)
=CatsWeight(A1) =猫体重(A1)
I set up a table with Cat Names & Weights on the Cat Sheet.我在 Cat Sheet 上设置了一张带有 Cat Names & Weights 的表格。 I setup a list of cat names on Sheet1.我在 Sheet1 上设置了一个猫名列表。
On sheet1 in the cell to the right of the cats name: CatsWeight()在猫名称右侧的单元格中的 sheet1 上:CatsWeight()
Here's my function:这是我的 function:
Function CatsWeight() As Double
Dim rngCell As Range
Set rngCell = Application.Caller
CatsWeight = WorksheetFunction.VLookup(rngCell.Offset(0, -1), Range("WeightTable"), 2)
End Function
HTH高温高压
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.