【问题标题】:ExecuteExcel4Macro , Is there any way to reference worksheet by index instead of its name in Application.ExecuteExcel4MacroExecuteExcel4Macro ,有没有办法通过索引而不是 Application.ExecuteExcel4Macro 中的名称来引用工作表
【发布时间】:2021-05-23 18:18:43
【问题描述】:

我想在不打开工作簿的情况下通过索引方法为工作表引用工作表。但是,我不知道该怎么做。网上的许多例子都是使用“Sheet1”,这不是我的情况。就我而言,每个工作簿都有其工作表名称,它们的名称都不同。

Sub excelfor_macro()
Dim p As String, f As String
Dim s As String, a As String
Dim my_array(1 To 8) As String
Dim r As Integer

Application.ScreenUpdating = False
p = "C:\Users\puntek\Desktop\"
f = "490XXZMAV31002S84D6A_002S84D68.xlsx"
s = SHEETNAME(1).Name  **'This is where, i want to reference by index, not worksheet name**

For r = 1 To 8
    a = Cells(r + 8, 3).Address 'start from row 9 the info
    my_array(r) = GetValue(p, f, s, a)
Next r
End Sub

Private Function GetValue(path, file, sheet, ref) 'This is getvalue function, the worksheetname will pass to sheet
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
    GetValue = "File Not Found"
    Exit Function
End If
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Address(, , xlR1C1)
GetValue = ExecuteExcel4Macro(arg)
End Function

【问题讨论】:

  • Worksheets(1) 会通过索引来引用它,只是希望顺序不要改变。
  • 嗨@braX,你的意思是替换arg = "'" &amp; path &amp; "[" &amp; file &amp; "]" &amp; Worksheets(1) &amp; "'!" &amp; _ Range(ref).Address(, , xlR1C1) 但这样不行。
  • 不,s = Worksheets(1).Name - 假设其余的工作正常 - 我想你必须先打开工作簿,先设置它,这样你才能访问集合。我不认为它会按照你想要的方式工作。

标签: excel vba excel-4.0


【解决方案1】:

打开工作簿以获取名称:

Dim wb as Workbook
p = "C:\Users\puntek\Desktop\"
f = "490XXZMAV31002S84D6A_002S84D68.xlsx"
Set wb = Workbooks.Open(p & f) ' or Set wb = Workbooks.Add(p & f)
s = wb.Worksheets(1).Name
' optionally close the workbook
wb.Close

【讨论】:

  • 您好,brax,感谢您的及时答复。我可以知道有没有办法在不打开工作簿的情况下获取工作表名称?这是因为,我正在处理数百个工作簿,打开的工作簿运行速度会明显变慢。
  • 嗯,根据这一点,您尝试这样做的方式可能会奏效 - 还没有尝试过...extendoffice.com/documents/excel/…。当你调试它时,它返回什么值?
  • 感谢链接,但链接方法需要打开工作簿才能获取工作表名称。调试时我得到 ERROR 2023
  • 是的,正如我所说,我认为没有办法按照您想要的方式进行操作。也许其他人会有一些想法。
猜你喜欢
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
相关资源
最近更新 更多