我一直在尝试将登录用户表单中的值输入到主模块代码中,该代码生成一个 sql 查询,该查询会将数据从我们的总账直接提取到 Excel 中。
为了在输入时屏蔽密码,我设置了一个用户表单,其中有两个文本框(用户名和密码)、一个登录命令按钮和一个取消按钮。我对登录单击命令进行了一些检查,检查用户详细信息字段不为空(下载请求中还有进一步的代码,将根据服务器的响应验证用户名是否正确)。
我无法通过的是我的主模块,该模块提供将生成查询字符串的类,以获取输入到用户表单中的项目。我使用硬编码的登录详细信息进行了测试,因此我知道代码有效。
下面是我的用户表单中与登录单击相关的部分以及围绕此用户表单调用的通用模块部分,然后是类模块的更新。主模块是通过单击工作表上的按钮触发的。
用户表单片段
Public Sub Login_Click()
'check user name is present
Dim corect_details As Integer
Dim uname As Integer
Dim pswrd As Integer
Dim nBIUsername As String
Dim nBIPassword As String
pswrd = 0
uname = 0
If Len(BIUsername) = 0 Then
MsgBox "please enter youre ISFE user name", vbOKOnly
Exit Sub
Else
uname = 1
nBIUsername = BIUsername
End If
If Len(BIPassword) = 0 Then
MsgBox "please enter a password", vbOKOnly
Exit Sub
Else
pswrd = 1
nBIPassword = BIPassword
End If
details = pswrd + uname
If details = 2 Then
MsgBox "username is " & BIUsername & vbCrLf & "password is " & BIPassword
Me.Hide
Else
End If
End Sub
主要模块片段
Dim nBIUsername As String
Dim nBIPassword As String
Sub showlogin()
Login.Show
GetDataFromBI
End Sub
Public Sub GetDataFromBI()
Dim BIReport As CBIReport: Set BIReport = New CBIReport
Load Login
With BIReport
.BIUsername = nBIUsername 'works when replaced with hardcoded username
.BIPassword = nBIPassword 'works when replaced with hardcoded Password
.REPORTPATH = MyReportPath
.ReportName = MyReportName
.FilterString = FilterString
.OutputOrigin = ThisWorkbook.Sheets("Output").Range("A1")
.GetData
If Not .IsLoginSuccessful Then MsgBox "Login not successful", vbCritical + vbOKOnly: GoTo CleanExit
If InStr(.LastDownloadStatus, "Success") > 0 Then
MsgBox "Download successful", vbOKOnly
Else
MsgBox "Download not successful", vbCritical + vbOKOnly
End If
End With
CleanExit:
Set BIReport = Nothing
End Sub
为了使您的 2 个模块级变量可用于用户窗体,请将它们声明为
Public
而不是使用 Dim
:
Public nBIUsername As String
Public nBIPassword As String
您需要删除同名变量:
Dim nBIUsername As String
Dim nBIPassword As String
从您的用户表单中,因为这些本地变量将隐藏公共变量。
您可以使用基于对话框的方法来返回数据,而不是使用全局/公共变量(这通常是不好的做法)。
在模块中创建一个类型来存储用户详细信息:
Public Type LoginDetals
Username As String
Password As String
IsValid As Boolean
End Type
添加退出按钮并将用户表单更改为:
Public Function getLogin() As LoginDetals
Me.Show vbModal
'// logic here
getLogin.Username = "bob"
getLogin.Password = "123"
getLogin.IsValid = True
End Function
Private Sub ExitButton_Click()
Unload Me
End Sub
然后在模块中您可以获取详细信息:
Sub foo()
Dim userDetails As LoginDetals
userDetails = Login.getLogin()
If (userDetails.IsValid) Then
GetDataFromBI userDetails
End If
End Sub
Function GetDataFromBI(userDetails As LoginDetals)
MsgBox "hello " & userDetails.Username
End Function