我尝试做的就是从另一张纸上获取一个单元格的值。在调试器中,当我跨过第一行时,我得到一个值错误。
从Sheet2单元格调用函数=getStr("20")
并收到 #VALUE!错误。我将参数作为整数传递20并且仍然有错误。
我可以调用Module1模块中的其他功能???
答案 0 :(得分:3)
您混淆了worksheet name属性和worksheet codename属性。
名称为摘要。代号是Sheet1。
你也不应该使用。选择。请参阅How to avoid using Select in Excel VBA。
答案 1 :(得分:2)
Jeeped已经告诉你代码的缺陷在哪里
这可能是您的代码的重构(注释中的解释):
Public Function getStr(iCol As Integer) As String
With Worksheets("Summary").Range("A52:J52") ' reference relevant sheet range (change "Summary" and range address to suit your needs)
If iCol <= .Columns.Count Then 'check if the passed column index fits the referenced range column number
getStr = .Cells(1, iCol).Value 'if so, then return the requested value
Else
gestr = "column index out of range!" ' otherwise inform the user she input the wrong column index
End If
End With
End Function
答案 2 :(得分:0)
这个怎么样?
Public Function getStr(iCol As Integer) As String
Dim rng As Range
Dim val As String
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
ws.Activate 'Activate the sheet before selecting a cell if another sheet is currently active
ws.Range("A1").Select 'not required if you want to get a value from a cell
Set rng = ws.Range("A52:J52") 'Correct way to set a range
'val = rng.Cells(1, iCol).Value 'Doesn't make sense as rng has only 10 columns in it
val = ws.Cells(1, iCol).Value 'Maybe you need this?
getStr = val
End Function