0

我已经为此工作了一段时间(我根本没有 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 错误告终。

再次,我将不胜感激任何帮助。谢谢!

4

1 回答 1

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
于 2013-08-23T21:04:20.727 回答