【发布时间】:2020-04-24 19:12:56
【问题描述】:
我正在尝试减少宏中的冗余,但我正在努力从锯齿状数组中获取一个元素并在其他地方使用它。 前提是单个工作簿,其中许多工作表按工作表名称组拆分为新文档,然后我可以将这些文档发送给流程所有者,以便他们只获取自己的数据。
以前我选择明确列出的工作表名称并粘贴到明确命名的新文档中,但我必须运行 10 个几乎相同的单独宏才能做到这一点,而且我听说在许多情况下 select 也是一个糟糕的选择.
以下是我最近的尝试,第一个问题是在 printOut 行我得到一个类型不匹配。
Sub CopyOut()
Dim printOut, groupNames, Group1, groupArray() As Variant
Dim n, j As Long
Dim reNamed, fileName As String
Dim ws As Worksheet
Dim wb1, wb2 As Workbook
groupNames = Array("Group 1", "Group 2", "Group 3", "Group 4") 'other arrays left off for length
Group1 = Array("FA_1A Report", "FA_1A", "FA_2ACS Report", "FA_2ACS", "FA_2BCS Report", "FA_2BCS", "FANUCMED Report", "FANUCMED", "FA_RRTP1 Report", "FA_RRPT1")
groupArray = Array(groupNames, Group1)
For n = 1 To UBound(groupArray)
fileName = "CS Data Sheet" & " " & Format(Date, "mmmyy") & "-" & groupArray(n - n)(n - 1) & ".xlsm" 'concat file name string. this is not just tacked on the end of reName because i use it on it's own later
reNamed = "C:\Users\xx\Desktop\" & fileName 'concat save location string
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Add 'create a new workbook, wb2
wb2.SaveAs fileName:=reNamed, FileFormat:=xlOpenXMLWorkbookMacroEnabled 'save with that name and location
printOut = Join(Application.Index(groupArray, n, 0), ",")
wb1.Sheets(printOut).Copy Before:=Workbooks(fileName).Sheets(1) 'copy the sheets for the group and paste into the newly created document
Next
End Sub
如果我完全取消 printOut 并输入一个特定的工作表名称,它只适用于那个工作表(当然),但我需要将多个工作表复制到每个新文档。
我也试过了:
For n = 1 To UBound(groupArray)
...
for j= LBound(groupArray(n)) To UBound(groupArray(n))
wb1.Sheets(groupArray(n)(j)).Copy Before:=Workbooks(fileName).Sheets(1)
next
next
遍历子数组并一次复制一张纸,但它给出的下标超出范围。在这个版本中,我尝试了各种方法将 groupArray(n)(j) 值转换为字符串或“工作表”类型以设置为变量并使用 sheet().copy 中的变量,但无济于事。
知道我哪里可能出错了吗? 非常感谢
编辑: 我通过将上面的代码包装在 split 中(当它只是一个字符串时试图将 printOut 用作数组)并修复 Index 的参数如下,但是生成的代码仍然需要工作,因为如果缺少一张表它不会运行。
printOut = Split(Join(Application.Index(groupArray(n), 1, 0), ","), ",")
【问题讨论】:
-
我仍然不太了解
groupNames、Group1和GroupArray应该如何协同工作。仅从这一事实来看,我想说您在这里的解决方案过于复杂。也许写一个Function,它将采用组名和索引并为您提供工作表名称。这样一来,您就可以简化主要逻辑,只需一次调用即可确定您需要的名称。 -
@PeterT groupArray 是属于每个组的工作表名称数组的数组(加上 groupNames,我只用它来命名文档)。绝对有可能我过于复杂了,但我不确定我是否理解函数的想法——通过它的索引提取工作表名称是我正在尝试(并且失败)通过在第二部分中迭代 n 和 j 来做的事情.如果我确实做了一个函数,我应该如何将它从 2d 传递到 .copy 中?谢谢,我只是 VBA 的试错学习者,非常感谢您的帮助