Excel宏在Excel 2016中不起作用-Selection.cut

时间:2019-08-30 14:54:20

标签: excel vba

我已经编写并使用了简单的Excel Macro来重新格式化Excel工作簿。这是一个简单的循环,可剪切并粘贴单元格,并在单元格为空时(即到达页面底部时)停止。

该宏在使用Excel 2013的笔记本电脑上可以正常工作。该文件不适用于拥有Excel 2016的同事。我的同事发现Selection.cut不会删除旧的,而是将旧的单元格内容保留在适当的位置因此while循环尽早结束。

我们尝试使用实际上相同的文件和相同的内容,但它对我有用,但对我的同事不起作用。我们认为Excel 2013和2016之间可能会有一些差异。代码如下:

Sub NewMACRO()

Dim y As Integer
Dim row As Integer
Dim test As String


y = 1
row = 1
test = "test"

Do While test <> ""

    Cells(y, 1).Select
    Application.CutCopyMode = False
    Selection.Cut
    Cells(row, 1).Select
    ActiveSheet.Paste

    y = y + 2
    Cells(y, 1).Select
    Selection.Cut
    Cells(row, 2).Select
    ActiveSheet.Paste

    y = y + 2
    Cells(y, 1).Select
    Selection.Cut
    Cells(row, 3).Select
    ActiveSheet.Paste

    y = y + 2
    Cells(y, 1).Select
    test = Selection
    row = row + 1

Loop

Cells(1, 1).Select

1 个答案:

答案 0 :(得分:0)

在代码中使用选择会在代码中造成很多时间错误。 我删除了所有选择代码,这些代码应该可以最大程度地减少此类问题。

Option Explicit

Sub NewMACRO()

Dim y As Long
Dim row As Long
Dim test As String

Dim ws As Worksheet
Set ws = Worksheets("Sheet1")

y = 1
row = 1
test = "test"

Do While test <> ""
    ws.Cells(y, 1).Cut ws.Cells(row, 1)

    y = y + 2
    ws.Cells(y, 1).Cut ws.Cells(row, 2)

    y = y + 2
    ws.Cells(y, 1).Cut ws.Cells(row, 3)


    '##Not sure what you want to do here.
    '##This is your original code where you populate the variable "test" with the selection value
    y = y + 2
    test = Cells(y, 1).Value
    row = row + 1


    '##I created this since it seems you want to use the variable "test" with some custom value populate to the variable
    'y = y + 2
    'Cells(y, 1).Value = test
    'If ws.Cells(row, 2) = "" Then
    '    ws.Cells(row, 1).ClearContents
    '    Exit Do
    'End If
    'row = row + 1

Loop

Cells(1, 1).Select

End Sub

您的代码让我有点困惑,因为它似乎没有使用变量test。 也许这样的事情是您希望将变量用于: 替换代码:

y = y + 2
test = Cells(y, 1).Value
row = row + 1

使用以下代码:

y = y + 2
Cells(y, 1).Value = test
If ws.Cells(row, 2) = "" Then
    ws.Cells(row, 1).ClearContents
    Exit Do
End If
row = row + 1