存储一些信息的Excel加载项

时间:2015-09-02 01:44:51

标签: excel vba excel-vba userform office-addins

我在Excel中创建了一个UserForm1并将其另存为加载项。这个加载项工作正常但它不存储我需要的一些数据(不存储它本身而不是存储在打开的excel中)。我必须在单元格A1和A2中存储一些信息(在A1用户名中,在A2今天的日期)。

当我运行此加载项时,UserForm1不包含这些值。

有没有办法存储UserName并获取更新日期?

以下是UserForm1的代码:

Private Sub UserForm1_Initialize()    
Me.DocumentName.Text = ActiveWorkbook.FullName
DocumentName.Visible = False

TextBoxDate.Value = Worksheets("Sheet1").Cells(2, "A").Value
TextBoxDate.Value = CDate(TextBoxDate.Value)

UserName.Visible = False
Userform1.UserName.Text = CStr(Range("A1").Value)

'If A1 is empty pops up a UserRegister form
If UserName = "" Then 
UserRegister.Show
End If    
End Sub

UserRegister表单代码:

Private Sub UserName_Change()
Sheets("Sheet1").Range("A1") = UserName.Text
End Sub

' I want to store the UserName, so the user does not have to enter it every single time
Private Sub CommandButtonGO_Click()
ThisWorkbook.Save 
Unload Me
End Sub

要获取日期,我只需在单元格A2中使用公式= TODAY()。我知道还有其他方法,但我发现这个很简单。

2 个答案:

答案 0 :(得分:0)

你能试试吗?

UserForm UserForm1

Private Sub UserForm1_Initialize()
    Me.DocumentName.Text = ActiveWorkbook.FullName
    DocumentName.Visible = False

    TextBoxDate.Value = ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
    'TextBoxDate.Value = CDate(TextBoxDate.Value)

    UserName.Visible = False
    UserForm1.UserName.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value

    'If A1 is empty pops up a UserRegister form
    If Len(UserName.Text) = 0 Then
        UserRegister.Show
    End If
    Debug.Print "Name: " & ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
    Debug.Print "Date: " & ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
End Sub

UserForm UserRegister

Private Sub UserName_Change()
    CommandButtonGO.Enabled = Not (UserName.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value)
End Sub

' I want to store the UserName, so the user does not have to enter it every single time
Private Sub CommandButtonGO_Click()
    ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Trim(UserName.Text)
    ThisWorkbook.Worksheets("Sheet1").Range("A2").Value = Now
    ThisWorkbook.Save
    Unload Me
End Sub

Private Sub UserRegister_Initialize()
    UserName.Text = UCase(Environ("USERNAME"))
End Sub

答案 1 :(得分:0)

好吧,我想办法怎么做。

要获取用户名,我使用了以下代码:Getting computer name using VBA(它还说明了如何获取用户名)

要获取当前的输入日期,我只需将输出代码更改为:

 ActiveCell.Offset(1, 0).Select 'Date column A
 ActiveCell.Value = Date

它在我的LOGfile excel中输出当前日期。

非常感谢你的帮助=)