合并两个宏-合并后,宏不起作用

时间:2018-08-02 05:56:00

标签: excel vba excel-vba

我正在尝试将两个VBA宏合并为一个;一键后我想运行两个VBA宏。

下面是两个宏。我尝试了单独的代码,但它们运行正常,但是当我尝试将其混合到一个宏中时,它将无法正常工作。

我的代码:

第一个宏

Sub copycolumns()
Dim lastrow As Long, erow As Long

lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow

Sheet1.Cells(i, 1).Copy
erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 1)

Sheet1.Cells(i, 3).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 2)

Sheet1.Cells(i, 7).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 3)

Sheet1.Cells(i, 6).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 4)

Sheet1.Cells(i, 5).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 5)

Sheet1.Cells(i, 9).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 6)
Next i
Application.CutCopyMode = False
Sheet2.Columns.AutoFit
Range("A1").Select

End Sub

第二个宏

<button class = "btn btn-primary"> A Button </ button>
import style1 from './style.css'
return <button className = {s['btn btn-primary']}> A Button </ button>;

一键后如何运行两个宏?

2 个答案:

答案 0 :(得分:1)

上面的代码中有很多问题,很可能是“合并”这两个代码所引起的问题。在获得一些使用VBA的经验并在Stack Overflow上阅读了其他问题,评论和答案之后,您也许可以修复这些问题。

同时,如果您的上述两个代码分别工作,则可以通过添加另一个调用其他两个子例程的子例程来使它们“一键式”运行:

Sub Page_layout_copy_columns()

Call Page_Layout
Call copycolumns

End Sub

将上述子例程粘贴到Visual Basic编辑器(VBE)中的模块中并运行它时,它将运行Page_Layout宏,然后运行copycolumns宏。

答案 1 :(得分:1)

您是否看过合并代码的一部分?

从此:

        Range("A1:I100").Select
    Range("I100").Activate
    With Selection
        .HorizontalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

对此:

        Range("A1:I100").Select
    Range("I100").Activate
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

可能减少到(但我尚未测试):

     With Range("A1:I100")
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

避免选择和激活显然是一种好习惯,请参见https://stackoverflow.com/a/20754562/4961700