宏上的命令按钮与从列表中选择宏不同

Command Button on macro acts differnet than selecting macro from list

我不明白为什么会这样,但我有一个宏可以根据国家/地区名称将数据从一个工作表移动到其他各种工作表。如果我 select 命令功能区中的宏(列表中的开发人员 tab/macros/select),则宏可以完美运行。如果我使用分配了宏的命令按钮,或使用调用宏的 button_click 方法,结果只是部分的。宏没有完成工作,但代码一直运行并且没有错误。我什至可以从列表中 select button_click 方法,它工作正常。为什么按钮的行为与 selecting 的宏列表不同?

Sub MoveButton_Click()

Call MoveDataToWorksheet

End Sub
Sub MoveDataToWorksheet()

Dim i As Variant
Dim pname As String
Dim rng As Range
Dim lastrow As Long
Dim wslastrow As Long
Dim ws As Worksheet
Dim count As Long
Dim rawdata As Worksheet

For Each ws In ThisWorkbook.Worksheets
    If ws.Name = "Raw_Data" Or ws.Name = "Charts" Or _
    ws.Name = "Tables" Then
    'skips the sheets I want to keep
    Else
        wslastrow = ws.Cells(Rows.count, "a").End(xlUp).Row
        If wslastrow >= 5 Then
            ws.Range("a5:r" & wslastrow).Delete
        Else
            ws.Range("a5:r" & 6).Delete
        End If
    End If
Next ws

Set rawdata = ThisWorkbook.Worksheets("Raw_Data")
lastrow = rawdata.Cells(Rows.count, "a").End(xlUp).Row
Set rng = rawdata.Range("a5:a" & lastrow)

For Each i In rng
    pname = Cells(i.Row, "a").Value

    For Each ws In ThisWorkbook.Worksheets
        If pname = ws.Name Then
            wslastrow = ws.Cells(Rows.count, "a").End(xlUp).Row + 1
            i.EntireRow.Copy
            If wslastrow >= 5 Then
                ws.Cells(wslastrow, "a").PasteSpecial
            Else
                ws.Cells(5, "a").PasteSpecial
            End If
        End If
    Next ws

        If pname = "South Carolina" Then
            i.EntireRow.Copy
            wslastrow = ThisWorkbook.Worksheets("SC").Cells(Rows.count, "a").End(xlUp).Row + 1
            If wslastrow >= 5 Then
                ThisWorkbook.Worksheets("SC").Cells(wslastrow, "a").PasteSpecial
            Else
                ThisWorkbook.Worksheets("SC").Cells(5, "a").PasteSpecial
            End If
        End If

        If pname = "Saudi Arabia" Then
            i.EntireRow.Copy
            wslastrow = ThisWorkbook.Worksheets("KSA").Cells(Rows.count, "a").End(xlUp).Row + 1
            If wslastrow >= 5 Then
                ThisWorkbook.Worksheets("KSA").Cells(wslastrow, "a").PasteSpecial
            Else
                ThisWorkbook.Worksheets("KSA").Cells(5, "a").PasteSpecial
            End If
        End If

        If pname = "United Arab Emirates" Then
            i.EntireRow.Copy
            wslastrow = ThisWorkbook.Worksheets("UAE").Cells(Rows.count, "a").End(xlUp).Row + 1
            If wslastrow >= 5 Then
                ThisWorkbook.Worksheets("UAE").Cells(wslastrow, "a").PasteSpecial
            Else
                ThisWorkbook.Worksheets("UAE").Cells(5, "a").PasteSpecial
            End If
        End If
Next i

Call FixWSFormulas

End Sub

关闭此问题:

pname = Cells(i.Row, "a").Value 中有一个隐含的 ActiveSheet,这意味着这可能 运行ning 针对不同的工作表,具体取决于您 运行 它来自宏列表还是命令按钮。

改为pname = rawdata.Cells(i.Row, "a").Value