我尝试在导入数据并从数据库插入行后保护名为 DATA 的工作表。但不幸的是,它并没有得到保护。我还需要锁定和隐藏列J,以便用户无法查看公式
这是我的代码:
Option Explicit
Sub GetDataFromADO()
'Input query'
'Dim dbQuery As String
'dbQuery = InputBox("Enter Query")
Dim pword As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveSheet.Unprotect Password:="star"
pword = InputBox("Please enter the password", "Password Required")
If pword <> "Audit2016" Then
MsgBox "You are not given access to view this!", vbCritical + vbOKOnly
Exit Sub
Else
Sheets("Data").Visible = True
On Error Resume Next
MsgBox "Check Worksheet DATA to view the results "
' Your code here
End If
'Declare variables'
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Dim iCols As Integer
Dim tbl As ListObject
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=;Initial Catalog=;Trusted_connection=Yes;Integrated Security=;"
objMyConn.Open
'Dim sSqL As String
'Set objMyCmd.ActiveConnection = objMyConn
'sSqL = "Select AccName,Underwriter,Auditor, UT_Score, Underwriter_Score from AUTUARIAL.dbo.AUDIT_CHECKLIST"
'objMyConn.Execute sSqL
'Set and Excecute SQL Command'
Dim u As String
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "SELECT FileID, AccName, Underwriter, Auditor,UT_Score,Underwriter_Score from Checklist"
'objMyCmd.CommandText = "SELECT CHECKLIST.FileID, CHECKLIST.AccName, CHECKLIST.Underwriter, CHECKLIST.Auditor, CHECKLIST.UT_Score, CHECKLIST.Underwriter_Score "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
'Open Recordset'
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
For iCols = 0 To objMyRecordset.Fields.Count - 1
Worksheets("Data").Cells(1, iCols + 1).Value = objMyRecordset.Fields(iCols).name
Next
'Copy Data to Excel'
Worksheets("Data").Range("A2").CopyFromRecordset objMyRecordset
'MsgBox "Report Generated Succesfully. View the results in worksheet called DATA !", vbOKOnly
ActiveSheet.Protect Password:="star"
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
答案 0 :(得分:1)
Worksheets("Data")
和ActiveSheet
是否相同?您正在操作名为Data的表并保护ActiveSheet。
Worksheets("Data").Protect
将确保其受保护而非随机活动表。