【发布时间】:2018-02-11 16:37:03
【问题描述】:
我要做的就是从不同的工作表中获取单元格的值。在调试器中,只要我越过第一行,就会出现值错误。
我从 Sheet2 单元格调用函数 =getStr("20") 并收到 #VALUE! 错误。我将参数作为整数传递 20,但仍然有错误。
我可以在我的 Module1 模块中调用其他函数???
【问题讨论】:
我要做的就是从不同的工作表中获取单元格的值。在调试器中,只要我越过第一行,就会出现值错误。
我从 Sheet2 单元格调用函数 =getStr("20") 并收到 #VALUE! 错误。我将参数作为整数传递 20,但仍然有错误。
我可以在我的 Module1 模块中调用其他函数???
【问题讨论】:
您混淆了worksheet name 属性和worksheet codename 属性。
名称是摘要。代号为Sheet1。
您也不应该使用 .Select。见How to avoid using Select in Excel VBA。
【讨论】:
Jeeped 已经告诉你代码的缺陷在哪里
这是您的代码的可能重构(cmets 中的解释):
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
【讨论】:
这个怎么样?
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
【讨论】: