【问题标题】:Using a variable for the title argument in InputBox在 InputBox 中为标题参数使用变量
【发布时间】:2013-10-03 20:13:47
【问题描述】:

我创建了一个 InputBox,它要求用户输入包含条目的最后一列的字母。根据索引,我希望标题是工作表名称。这是我写的代码:

Dim LastEntryCol As String  
Dim ShtName As Variant  
Set ShtName = ThisWorkbook.Sheets(2) '****The number 2 will need to be changed to an index.  For now it's hard-entered.  
LastEntryCol = Application.InputBox("What is the letter of the last column containing entry labels?", ShtName)`

当我运行它时,我收到错误 1004“对象 '_Application' 的方法 'InputBox' 失败”。我怀疑这与我设置 ShtName 的方式有关,因为如果我将标题参数替换为“万岁编码!”之类的内容,代码将正常运行。

谁能向我解释出了什么问题以及我该如何解决?谢谢!

【问题讨论】:

    标签: excel vba variables inputbox


    【解决方案1】:

    您传递的是整个WorkSheet object,而不仅仅是它的名字。试试这个:

    Dim LastEntryCol As String
    Dim ShtName As String
    ShtName = ThisWorkbook.Sheets(2).Name '****The number 2 will need to be changed to an index.  For now it's hard-entered.
    LastEntryCol = Application.InputBox("What is the letter of the last column containing entry labels?", ShtName)
    

    【讨论】:

    • 完美!非常感谢您解释发生了什么。
    【解决方案2】:

    Sheets 是一个集合,因此要获取您需要使用的名称

    ShtName = ThisWorkbook.Sheets.Item(2).Name
    

    也很确定这将始终是一个字符串,因此您可以使用 Dim ShtName As String 并避免设置。

    【讨论】:

    • OP 使用 Set 是正确的,因为您需要它将新对象(在本例中为 WorkSheet)分配给变量。现在(与您的提案或我的提案相同),您只是将值分配给 String 变量(或 Variant 变量,理解为字符串),因此您不能使用 Set (您必须删除它;您的代码触发错误)。
    • 是的,这就是为什么我说他可以通过将数据类型指定为字符串并使用名称属性来避免使用集合。虽然我忘记了 VBA Collections Item 是通过使用您的示例中的索引来暗示的。
    • 不,您不需要将变量声明为字符串。如前所述,您的代码(= 用作变体)会触发错误。 “设置”不是因为变体/字符串类型,而是因为将新对象分配给变量。字符串值不是一个新对象,而是一个值,因此您不能将 Set 与它一起使用。
    • 抱歉刚刚意识到你指的是没有意识到我把它留在了那里。已编辑
    • 没问题;只是来帮忙:)
    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 2014-02-03
    • 2021-05-27
    • 2019-06-23
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多