【问题标题】:Sheet order autopopulate with VBA Excel macro使用 VBA Excel 宏自动填充工作表顺序
【发布时间】:2020-12-02 13:05:40
【问题描述】:

我想在 Excel 中自动填充工作表编号(最好使用 VBA 宏)。这不是一个标准的工作表编号,它从我的工作簿的一开始就开始了。我要订购的纸张从文档末尾附近开始。在右下角,它们被标识为 OT 1 of 5,这意味着“OT”表是第 5 个可用的。

总页数取决于“前页”中定义的单位数并除以 2(我希望一张页中有 2 个单位)。

因为我的代码还包括这个平面数字的表格自动填充,类似于我想要实现的顺序编号,它看起来如下:

 Sub otdr()

 Dim i As Long, j As Long
 Dim xNumber As Long, yNumber As Long
 Dim otdr As Range
 Dim xName As String
 Dim ws As Worksheet

 Application.ScreenUpdating = False

 Set ws = Sheets("OTDR TRACE - 1")
 Set otdr = ws.Range("Q46")  'the cell, where order of sheets is included
 xNumber = Sheets("Frontsheet").Range("D32").Value  'the cell where number of flats is included
 yNumber = xNumber / 2   'dividing number of flats by 2

 For j = 1 To xlNumber
 otdr = "OT " & j & " of " & Number  ' ordering sheets
 Next

 For i = 1 To (xNumber / 2)
 ws.Copy After:=ActiveWorkbook.Sheets(ws.Index + i - 1)
 ActiveSheet.Name = "OTDR TRACE - " & (i + 1)  'autopopulating new sheets
 Next

 ws.Activate

 Application.ScreenUpdating = True

 End Sub

新工作表已添加,但我的顺序有误。我添加了 3 张纸,这很好,但它们的最终数量是 3,而不是 5。我不知道为什么“0”出现而不是正确的数字。我做错了什么?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    其中一个解决方案如下所示:

     Sub otdr()
    
     Dim i As Long
     Dim xNumber As Long, yNumber As Long
     Dim otdr As Range
     Dim xName As String
     Dim ws As Worksheet
    
     Application.ScreenUpdating = False
    
     Set ws = Sheets("OTDR TRACE - 1")
     Set otdr = ws.Range("Q46")
     xNumber = Sheets("Frontsheet").Range("D32").Value
     yNumber = xNumber / 2   'total amount of our sheets in the order
    
     For i = 1 To (xNumber / 2)
     otdr = "OT " & (i + 1) & " of " & (yNumber + 1)
     ws.Copy After:=ActiveWorkbook.Sheets(ws.Index + i - 1)
     ActiveSheet.Name = "OTDR TRACE - " & (i + 1)
     Next
    
     ws.Activate
     otdr = "OT 1 of " & (yNumber + 1)
    
     Application.ScreenUpdating = True
    
     End Sub
    

    我们不再需要j 变量。我们可以基于现有的i 变量来做所有事情。

    接下来,我们应该将所有内容保持在一个循环中,在表格填充之前,我们应该定义这些表格的总数:

        otdr = "OT " & (i + 1) & " of " & (yNumber + 1)
    

    但是,由于第一张纸的顺序错误,我们可以预防性地再次使用

        otdr = "OT 1 of " & (yNumber + 1)
    

    因为我们在订单中的第一张工作表在循环完成后被激活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多