Excel在运行此代码时一直处于冻结状态

Excel在运行此代码时一直处于冻结状态,excel,vba,Excel,Vba,我通过命令按钮(ActiveX)运行函数,当我运行它时,excel每隔一段时间就会冻结一次。有人知道为什么吗 代码从空的格式化工作表中复制一个范围,并将其插入到放置命令按钮的工作表中(在其中插入新的月份) 然后我在8张不同的工作表中把它称为 Private Sub cmd_NyMndBravida_Click() Dim navnArk As String navnArk = ActiveSheet.Name nyMndFunction (navnArk) End S

我通过命令按钮(ActiveX)运行函数,当我运行它时,excel每隔一段时间就会冻结一次。有人知道为什么吗

代码从空的格式化工作表中复制一个范围,并将其插入到放置命令按钮的工作表中(在其中插入新的月份)

然后我在8张不同的工作表中把它称为

Private Sub cmd_NyMndBravida_Click()
    Dim navnArk As String

    navnArk = ActiveSheet.Name
    nyMndFunction (navnArk)

End Sub

我相信这是为了
CutCopyMode
模式在
wstEnt.Range(“B4”)之后保持活动状态。插入移位:=xlDown

因此,在该行后面插入
Application.CutCopyMode=False
语句:

Function nyMndFunction(navnArk As String)
    Dim gammelMnd As String, monthNames As String

    ...

    wstEnt.Range("B4").Insert Shift:=xlDown

    Application.CutCopyMode = False '<-- statement to be inserted

    wstEnt.Cells(4, 2).value = nyMnd
    wstEnt.Cells(3, 3).Select
End Function
其中使用[Split()]/)函数从带分隔符的字符串中返回数组


正如您从链接文档中所看到的,它返回一个基于零的数组,以便上面的代码在处理
iMonth
index

时能够处理它。感谢您的解决,并就我的代码给了我建设性的建议!我真的很感激:)
Function nyMndFunction(navnArk As String)
    Dim gammelMnd As String, monthNames As String

    ...

    wstEnt.Range("B4").Insert Shift:=xlDown

    Application.CutCopyMode = False '<-- statement to be inserted

    wstEnt.Cells(4, 2).value = nyMnd
    wstEnt.Cells(3, 3).Select
End Function
Private Sub cmd_NyMndBravida_Click()

    nyMndFunction ActiveSheet '<--| just pass the worksheet itself, without having to evaluate its name here and then evaluate it back to the worksheet object in 'nyMndFunction'

End Sub
Option Explicit

Sub nyMndSub(wstEnt As Worksheet)
    Dim monthNames As String, nyMnd As String
    Dim iMonth As Long
    Dim wstMal As Worksheet

    Set wstMal = Worksheets("Mal")

    monthNames = "JANUAR,FEBRUAR,MARS,APRIL,MAI,JUNI,JULI,AUGUST,SEPTEMBER,OKTOBER,NOVEMBER,DESEMBER" '<--| month names list string

    iMonth = InStr(monthNames, wstEnt.Cells(4, 2).value) '<--| look for the cell content in the month names list
    If iMonth > 0 Then '<--| if found...
        iMonth = Len(Left(monthNames, iMonth)) - Len(Replace(Left(monthNames, iMonth), ",", "")) + 1 '<--| get its "position" inside the list by counting the delimiter occurrences before it and skip to the "next" one
        If iMonth = 12 Then iMonth = 0 '<--| if the "next position" is outside the 12-elements month names list then skip back to the first element
        nyMnd = Split(monthNames, ",")(iMonth) '<--| get the month names in the finally selected "position"

        wstMal.Range(wstMal.Cells(1, 1), wstMal.Cells(41, 11)).Copy '<-- do the copy juts when needed
        With wstEnt
            .Range("B4").Insert Shift:=xlDown
            Application.CutCopyMode = False '<--| exit cutcopymode as soon as possible, i.e. after the clipboard content hs been exploited and no longer needed
            .Cells(4, 2).value = nyMnd
            .Cells(3, 3).Select
        End With
    End If
End Sub