当我尝试关闭使用此用户窗体操作的工作簿时关闭我的用户窗体

时间:2018-05-24 05:33:49

标签: excel-vba vba excel

/ 此代码用于excel VBA中Userform中的命令按钮 /

Function CreateLabel(ByVal b As Integer, ByVal c As Long, ByVal d As String)
Application.DisplayAlerts = False
Dim i As Long
i = i + b

For labelCounter = 1 To i
On Error GoTo Count

    Set theLabel = UserForm3.Controls.Add("Forms.Label.1", "Cart" & labelCounter, True)
    With theLabel
        .Caption = d
        .Left = 10
        .Width = 50
        .Top = 10 * labelCounter
    End With

    Set theLabel2 = UserForm3.Controls.Add("Forms.Label.1", "Cart" & labelCounter, True)
    With theLabel2
        .Caption = c
        .Left = 70
        .Width = 50
        .Top = 10 * labelCounter
    End With
Count:

    Next labelCounter
    UserForm3.TextBox1.Value = UserForm3.TextBox1.Value + c


    h = Sheet1.TextBox1.Value

     Dim f As Workbook

    Set f = Workbooks.Open("C:\Users\39800\Desktop\Hexa_DB.xlsx") /*Here workbook is opened*/

    l = f.Worksheets("sheet2").Select()
    f.Worksheets("sheet2").UsedRange().Select
    ActiveCell.SpecialCells(xlLastCell).Select
    xLastRow = ActiveCell.Row
    xLastCol = ActiveCell.Column

    For q = 2 To xLastRow
    If (Cells(q, 1).Value = h) Then
    Cells(q, 2) = Format(UserForm3.TextBox1.Value, "Currency")
    f.Save

    f.Close /*Here it is closing my userform also*/

    End If

    Next q


    MsgBox "You have Successfully added this item to cart"
    Exit Function


End Function

1 个答案:

答案 0 :(得分:0)

在打开新工作簿之前添加对当前工作簿的引用,

Dim wbkCurrent as workbook
Set wbkCurrent = ActiveWorkbook

然后在f.Save添加wbkCurrent.Activate

之后