使用在对象名的变量与声明

问题描述 投票:1回答:2

我有一个Excel宏读取从另一片的特定列的内容。我想用在表名的变量在with语句中,但不断收到错误消息“运行时错误,所需的对象”,在每行

我已经搜查了如何在对象名称中使用变量,并尝试过,但都无济于事。

此代码的工作

With Blad2
strData = Range(id & "1") & vbLf & vbLf
    For Each c In .Range(id & "2:" & id & "10")
        If c.Value <> "" Then
            strData = strData & " - " & c.Value & vbLf
        End If
    Next c
End With

此代码失败。我知道肯定可变BLD有一个数值,测试与MSGBOX

With ("Blad" & bld)
strData = Range(id & "1") & vbLf & vbLf
    For Each c In .Range(id & "2:" & id & "10")
        If c.Value <> "" Then
            strData = strData & " - " & c.Value & vbLf
        End If
    Next c
End With

任何线索我怎么能得到这个工作?

excel vba
2个回答
2
投票

一个工作表可以被称为4个方面:

  • 其指数;
  • 其标签上的名称;
  • 以其CodeName,这是默认相同的标签的名称,除非后者被改变;
  • 用的变量;

前一段时间我写在这里这个答案 - https://stackoverflow.com/a/52721327/5448626


当你写With Blad2,然后Blad2是工作表的代号。例如,这里的一个:

enter image description here

因此,它已经是一个变量,Excel可以识别它。在另一方面,With ("Blad" & bld)是一个字符串,而不是一个工作表变量。

为了使它工作,使用With Worksheets("Blad" & bld),使用工作表的工作表名称。


2
投票

你正在尝试是使用Variable Variable为SheetCode名称。你不能那样做。为了达到你想要的东西,试试这个...

Dim bld As Long: bld = 2
Dim shtCode As String

shtCode = "Blad" & bld

With Sheets(ThisWorkbook.VBProject.VBComponents(shtCode).Properties("Name").Value)
    Debug.Print .Name
End With
© www.soinside.com 2019 - 2024. All rights reserved.