如何使用VBA添加计算机名和用户名

时间:2018-09-13 17:32:31

标签: excel vba excel-vba environment-variables

如何使用网络上每台Windows 7和10计算机的计算机名称和用户名作为要输入到表中的变量。

我正在使用隐藏表上的表格将保存日志记录到工作簿中。这些文件从网络计算机打开并保存到网络计算机。我想知道谁保存在每个工作簿上

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim ws As Worksheet
Set ws = Sheets("EDITS")
Dim tbl As ListObject
Set tbl = ws.ListObjects("Table1")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

'DIM SOME MORE OBJECTS
Dim computername, username As String
Dim ComputerNameLen As Long

computername = Environ("computer name") 'Get computer name
username = Environ("user name") 'Get user name


SavePrompt.Show

With newrow
    .Range(1) = Now
    .Range(2) = SavePrompt.TextBox1.Text
    .Range(3) = computername
    .Range(4) = username 

End With

Unload SavePrompt
Unload computername
Unload username
End Sub

Range(1)和Range(2)都正确填写,但Ranges(3)&(4)却什么也没有出现

我认为我的物品有问题吗?

1 个答案:

答案 0 :(得分:1)

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim ws As Worksheet
Set ws = Sheets("EDITS")
Dim tbl As ListObject
Set tbl = ws.ListObjects("Table1")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

'DIM SOME MORE OBJECTS
Dim computername As String
Dim username As String
computername = Environ("computername")
username = Environ("username") 

    SavePrompt.Show

With newrow
    .Range(1) = Now
    .Range(2) = SavePrompt.TextBox1.Text
    .Range(3) = computername
    .Range(4) = username

End With

Unload SavePrompt

End Sub