我一直在研究这个问题(我根本没有体验过VBA),但我一直都会遇到错误,所以我们就是这样。
设置:
为简单起见,我在工作簿中有两个工作表。第一个“每日订单”是我所有产品的列表,每行是不同的产品(约1,000),每列指示产品的不同信息(即ID,成本,重量等)。
第二个“模板”是一个定价模板,在给定产品信息时,将生成定价表。
目的: 创建一个VBA宏以遍历“每日订单”工作表的每一行,并为每一行制作模板表的副本,并将某些信息附加到该新工作表。
什么行不通:
Sub GeneratePriceBook()
Dim rw As Range
Dim temp As Worksheet
Dim ws As Worksheet
Dim daily As Worksheet
Set daily = Worksheets("Daily Order")
Set temp = Worksheets("Template")
temp.Activate
For Each rw In daily.Rows
temp.Copy After:=Sheets(Sheets.Count)
Set ws = Sheets(Sheets.Count)
ws.Name = rw.Value
With ws
.Range("A6").Formula = "='Daily Order'!B" & rw.Row
.Range("B6").Formula = "='Daily Order'!B" & rw.Row
.Range("A3").Formula = "='Daily Order'!Q" & rw.Row
.Range("E36").Formula = "='Daily Order'!M" & rw.Row
.Range("E36").Formula = "='Daily Order'!Y" & rw.Row
.Range("E37").Formula = "='Daily Order'!L" & rw.Row
End With
Next rw
End Sub
错误类型:
我花了相当多的时间试图找出某些我认为可能会造成麻烦的方面,但我最终会遇到424错误或1004错误。
再次,我将非常感谢任何帮助。 谢谢!
答案 0 :(得分:2)
我认为这就是你要找的东西:
Sub GeneratePriceBook()
Dim wsDaily As Worksheet
Dim wsTemp As Worksheet
Dim lVisibility As XlSheetVisibility
Dim strSheetName As String
Dim rIndex As Long
Dim i As Long
Set wsDaily = Sheets("Daily Order")
Set wsTemp = Sheets("Template")
lVisibility = wsTemp.Visible 'In case template sheet is hidden
wsTemp.Visible = xlSheetVisible
For rIndex = 2 To wsDaily.Cells(Rows.Count, "A").End(xlUp).Row
'Ensure valid sheet name
strSheetName = wsDaily.Cells(rIndex, "A").Text
For i = 1 To 7
strSheetName = Replace(strSheetName, Mid(":\/?*[]", i, 1), " ")
Next i
strSheetName = Trim(Left(WorksheetFunction.Trim(strSheetName), 31))
'Make sure the sheet name doesn't already exist
If Not Evaluate("IsRef('" & strSheetName & "'!A1)") Then
wsTemp.Copy After:=Sheets(Sheets.Count)
With Sheets(Sheets.Count)
.Name = strSheetName
.Range("A6").Formula = "='" & wsDaily.Name & "'!B" & rIndex
.Range("B6").Formula = "='" & wsDaily.Name & "'!B" & rIndex 'You are referencing the same cell as in A6?
.Range("A3").Formula = "='" & wsDaily.Name & "'!Q" & rIndex
.Range("E36").Formula = "='" & wsDaily.Name & "'!M" & rIndex
.Range("E36").Formula = "='" & wsDaily.Name & "'!Y" & rIndex 'You are putting a second formula in E36?
.Range("E37").Formula = "='" & wsDaily.Name & "'!L" & rIndex
End With
End If
Next rIndex
wsTemp.Visible = lVisibility 'Set template sheet to its original visible state
Set wsDaily = Nothing
Set wsTemp = Nothing
End Sub