【问题标题】:cant access a different sheet getting #VALUE! error无法访问获得#VALUE 的其他工作表!错误
【发布时间】:2018-02-11 16:37:03
【问题描述】:

我要做的就是从不同的工作表中获取单元格的值。在调试器中,只要我越过第一行,就会出现值错误。

我从 Sheet2 单元格调用函数 =getStr("20") 并收到 #VALUE! 错误。我将参数作为整数传递 20,但仍然有错误。

我可以在我的 Module1 模块中调用其他函数???

【问题讨论】:

  • 虽然 VBE 的图像在这种情况下很有用,但您不应该期望人们自愿花时间帮助您重新键入代码。相关代码应该已经添加到代码块中的问题中。
  • 附加信息here和here和here等

标签: vba excel


【解决方案1】:

您混淆了worksheet name 属性和worksheet codename 属性。

名称是摘要。代号为Sheet1。

您也不应该使用 .Select。见How to avoid using Select in Excel VBA。

【讨论】:

  • 此外,A52:J52 没有 20 列,因此您在任何情况下都无法检索到合法值。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这个怎么样?

    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
    

    【讨论】:

    • .Activate 和 .Select 在 '从 Sheet2 单元格中调用函数'的 UDF 中完全不合适。
    • 同意。这就是我写的cmets。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2020-02-08
    • 2016-05-26
    相关资源
    最近更新 更多