我有一个报告,我正在建立我将从3个不同的查询插入数据的地方。导出为CSV时,我们的报告工具不会将所有列命名(列名实际上在报告系统中合并)。我想使用宏为各列添加标题行描述,但是我遇到了麻烦。
我正在尝试使用数组和循环来完成此任务。当我刷新报表时,其中的工作表名称和单元格引用将保持静态。我将不仅仅是工作簿中的这些工作表,所以我只想"目标"具有此宏的特定数据表。行中的宏错误会立即进行with worksheets(count)
。错误代码' 424' "对象要求"。我认为它是因为Excel不是"看到"我的数组值作为工作表名称,但我不知道如何转换它。
我愿意以更有效的方式接近这项任务。
提前感谢您的帮助!
Sub Headerfill()
' Headerfill Macro
' Macro to fill in blanks in header row from data dump
Dim WorkSheets As Variant
Dim Count As Integer
WorkSheets = Array( _
"Sheets(""VH Own Brand Component"")", _
"Sheets(""VH Sales and Inventory Component"")", _
"Sheets(""VH Comp Sales Component"")")
Count = 0
Do While Count < 3
With WorkSheets(Count)
.Range("B3").Value = "A Name"
.Range("D3").Value = "B Name"
.Range("F3").Value = "C Name"
.Range("H3").Value = "First"
.Range("I3").Value = "Last"
.Range("K3").Value = "VName"
End With
Count = Count + 1
Loop
End Sub
答案 0 :(得分:2)
根据评论编辑。这应该使图纸顺序或名称更改没有实际意义。函数取自Chip。有关codename属性的信息,请参阅MSDN。
Sub Headerfill()
Dim ws As Variant
Dim wsCode As Worksheet
ws = Array(4, 5, 7)
For i = 0 To UBound(ws)
Set wsCode = getCodeName("Sheet" & ws(i))
With wsCode
.Range("B3").Value = "A Name"
.Range("D3").Value = "B Name"
.Range("F3").Value = "C Name"
.Range("H3").Value = "First"
.Range("I3").Value = "Last"
.Range("K3").Value = "VName"
End With
Next
End Sub
Function getCodeName(codeName As Variant) As Worksheet
Dim ws As Worksheet
For Each ws In ThisWorkbook.WorkSheets
If StrComp(ws.codeName, codeName, vbTextCompare) = 0 Then
Set getCodeName = ws
Exit Function
End If
Next ws
End Function
答案 1 :(得分:0)
更新以包含BruceWaynes建议以保持与原始代码意图的内联。 Findwindow的建议也很好,但选择下面的答案。还发现我正在引用的一个工作表有省略号,完成工作表名称(由于长度)与我导出的报告的全名,导致下标错误,直到我更正。
Sub Headerfill()
' Headerfill Macro
' Macro to fill in blanks in header row from data dump
Dim WS As Variant
Dim i As Integer
WS = Array(_
"VH Own Brand Component",_
"VH Sales and Inventory Compo...",_
"VH Comp Sales Component")
For i = 0 To UBound(WS)
With WorkSheets(WS(i))
.Range("B3").Value = "A Name"
.Range("D3").Value = "B Name"
.Range("F3").Value = "C Name"
.Range("H3").Value = "First"
.Range("I3").Value = "Last"
.Range("K3").Value = "VName"
End With
Next
End Sub