Error 3421 Data Type Connection Error Multy Column Combobox - vba

I have a scenario where in I have to save "STATUS" code into table from a "COMBO BOX". This Combo Box shows "Status ID" and "Status Description" together. But while saving I need to save only "Status ID"
Following is the code for the complete form functionality. Error is occurring on click of "SAVE" button. On line where I am assigning the value from combo to "Recordset Column" on line # 77 or 90.
' rs![status_ID] = Me.cboStatus.Column(1)
Option Compare Database
Option Explicit
Dim db As Database
Dim rs, rs2, rs3 As Recordset
Dim SQL, SQL1, SQL2 As String
Dim intChk As Integer
Private Sub btnFirst_Click()
If Not rs.BOF Then
rs.MoveFirst
Set_Data
End If
If rs.EOF Then
rs.MovePrevious
End If
End Sub
Private Sub btnLast_Click()
If Not rs.EOF Then
rs.MoveLast
Set_Data
End If
If rs.EOF Then
rs.MovePrevious
End If
End Sub
Private Sub btnNew_Click()
SQL2 = "select Max(job_ID) as JID from tbl_mst_JobOrder"
Set rs3 = CurrentDb.OpenRecordset(SQL2, dbOpenDynaset, dbSeeChanges)
If Not rs3.EOF And Not rs3.BOF Then
Me.txtJobID = rs3!JID + 1
End If
Set rs3 = Nothing
TxtSetEmpty
End Sub
Private Sub btnNext_Click()
If Not rs.EOF Then
rs.MoveNext
Set_Data
End If
If rs.EOF Then
rs.MovePrevious
End If
End Sub
Private Sub btnPrevious_Click()
If Not rs.BOF Then
rs.MovePrevious
Set_Data
End If
If rs.BOF Then
rs.MoveNext
End If
End Sub
Private Sub btnSave_Click()
Dim SQL As String
IfEmpty
Dim sqlShift As String
If intChk = 1 Then
intChk = 0
Exit Sub
Else
SQL = "select job_ID from qryJobDetails " _
& "where job_ID = " & Me.txtJobID
Set rs2 = CurrentDb.OpenRecordset(SQL)
If Not rs2.EOF Then
Dim CHK As String
Me.lblChk.Caption = rs2![job_ID]
End If
Set rs2 = Nothing
If Me.txtJobID.Value = Me.lblChk.Caption Then
Dim msgUpd, msgNew, strCobSt As String
strCobSt = Me.cboStatus.Column(1)
msgUpd = "Do you want to update Location ID " & Me.lblChk.Caption
If MsgBox(msgUpd, vbYesNo, "Location Update") = vbYes Then
rs.Edit
rs![job_Date] = Me.dtpJDate.Value
rs![job_Desc] = Me.txtJobDesc
rs![loc_ID] = Me.txtLocID
rs![status_ID] = Me.cboStatus.Column(1)
rs![Comments] = Me.txtComment
rs.Update
RefreshListBox
End If
Else
msgNew = "Do you want to add New Location"
If MsgBox(msgNew, vbYesNo, "Add New Location") = vbYes Then
rs.AddNew
rs![job_ID] = Me.txtJobID
rs![job_Date] = Me.dtpJDate.Value
rs![job_Desc] = Me.txtJobDesc
rs![loc_ID] = Me.txtLocID
rs![status_ID] = Me.cboStatus.Column(1)
rs![Comments] = Me.txtComment
rs.Update
RefreshListBox
End If
End If
End If
End Sub
Private Sub Form_Load()
Set db = CurrentDb
SQL = "Select status_ID, status_Desc from tbl_mst_Status order by status_ID"
Set rs2 = db.OpenRecordset(SQL)
Do Until rs2.EOF
Me.cboStatus.AddItem rs2![status_ID] & "|" & rs2![status_Desc]
rs2.MoveNext
Loop
Set rs2 = Nothing
Set rs = db.OpenRecordset("qryJobDetails", dbOpenDynaset, dbSeeChanges)
RefreshListBox
Set_Data
End Sub
Private Sub Set_Data()
If Not rs.BOF And Not rs.EOF Then
Me.txtJobID = rs![job_ID]
Me.dtpJDate = rs![job_Date]
Me.txtJobDesc = rs![job_Desc]
Me.txtLocID = rs![loc_ID]
Me.txtLocDec = rs![location_desc]
Me.cboStatus = rs![status_ID] & "|" & rs![status_Desc]
Me.txtComment = rs![Comments]
End If
End Sub
Private Sub RefreshListBox()
Me.lstJobOrd.RowSource = ""
Me.lstJobOrd.AddItem "Job Order" & ";" & "Job Date" & ";" & "Job Description" & ";" _
& "Loc Description" & ";" & "Loc ID" & ";" & "Sta ID" & ";" _
& "Sta Desc" & ";" & "Comments"
rs.MoveFirst
Do Until rs.EOF
Me.lstJobOrd.AddItem rs![job_ID] & ";" & rs![job_Date] & ";" & rs![job_Desc] & ";" _
& rs![location_desc] & ";" & rs![loc_ID] & ";" & rs![status_ID] & ";" _
& rs![status_Desc] & ";" & rs![Comments]
rs.MoveNext
Loop
rs.MoveFirst
End Sub
Private Sub TxtSetEmpty()
Me.txtJobDesc = ""
Me.dtpJDate = Now()
Me.txtLocDec = ""
Me.cboStatus = ""
Me.txtComment = ""
Me.txtLocID = ""
End Sub
Private Sub lstJobOrd_Click()
With Me.lstJobOrd
Me.txtJobID.Value = .Column(0)
Me.dtpJDate.Value = .Column(1)
Me.txtJobDesc.Value = .Column(2)
Me.txtLocDec.Value = .Column(3)
Me.txtLocID.Value = .Column(4)
Me.cboStatus.Value = .Column(5)
Me.txtComment.Value = .Column(7)
End With
End Sub
Private Sub IfEmpty()
Dim txtCtr As Control
Dim cboCtr As Control
Dim Str As String
Str = Empty
For Each txtCtr In Me.Controls
If TypeOf txtCtr Is TextBox Then
If IsNullOrEmpty(txtCtr) Then
txtCtr.BackColor = RGB(119, 192, 212)
txtCtr.BorderColor = RGB(157, 187, 97)
Str = Str & txtCtr.Tag & vbNewLine
Else
txtCtr.BackColor = vbWhite
txtCtr.BorderColor = RGB(192, 192, 192)
End If
End If
Next txtCtr
For Each cboCtr In Me.Controls
If TypeOf cboCtr Is ComboBox Then
If IsNullOrEmptyCbo(cboCtr) Then
cboCtr.BackColor = RGB(119, 192, 212)
cboCtr.BorderColor = RGB(157, 187, 97)
Str = Str & cboCtr.Tag & vbNewLine
Else
cboCtr.BackColor = vbWhite
cboCtr.BorderColor = RGB(192, 192, 192)
End If
End If
Next cboCtr
If IsNull(Str) Or Str = "" Then
Exit Sub
Else
MsgBox "Please enter data in the highlited fields. " & vbNewLine & _
String(52, "_") & vbCrLf & Str, vbInformation + vbOKOnly, "Data not Complete"
intChk = 1
Exit Sub
End If
End Sub
Private Sub txtLocDec_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 113 Then
DoCmd.OpenForm "frmLocSer", acNormal, , , acFormAdd, acWindowNormal
End If
End Sub`

Related

MS Access VBA export table to text file

I am using the code below to export data from Access table to text file so i can use it in mySQL.
My export code:
Sub ExpTblCity()
On Error GoTo Err_Handler
Dim t, sText, rText, LResult As String
Close #1
t = "INSERT INTO `tblcity` (`city_id`,`city_name`,`city_enabled`) VALUES "
Dim rst As DAO.Recordset
Open Application.CurrentProject.Path & "\2-TblCity.txt" For Output As #1
Print #1, t
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblCity", dbOpenSnapshot)
Do While Not rst.EOF
rText = "'NULL'"
sText = "('" & rst!CityID & "','" & rst!City & "','0'),"
LResult = Replace(sText, rText, "NULL")
Print #1, LResult
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
t = ""
sText = ""
rText = ""
LResult = ""
Close #1
Exit_This_Sub:
Exit Sub
Err_Handler:
If Err = 0 Then
ElseIf Err = 94 Then
Resume Next
ElseIf Err = 3265 Then
Resume Next
Else
MsgBox "Error #: " & Err.Number & " " & Err.Description
End If
Resume Exit_This_Sub
End Sub
Output from the above code:
INSERT INTO `tblcity` (`city_id`,`city_name`,`city_enabled`) VALUES
('1','London','0'),
('2','Paris','0'),
('3','Rome','0'),
('4','Athens','0'),
('5','Madrit','0'),
The code is working fine BUT i am trying to replace IN THE LAST ROW the last , with ;.
Correct output:
...
('4','Athens','0'),
('5','Madrit','0');
Any idea.
It will be convenient to save it by using an array and use the Join Function.
Sub ExpTblCity()
On Error GoTo Err_Handler
Dim t As String, sText As String, rText As String, LResult As String
Dim vResult() As Variant
Dim n As Long
Close #1
t = "INSERT INTO `tblcity` (`city_id`,`city_name`,`city_enabled`) VALUES "
Dim rst As DAO.Recordset
Open Application.CurrentProject.Path & "\2-TblCity.txt" For Output As #1
Print #1, t
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblCity", dbOpenSnapshot)
Do While Not rst.EOF
n = n + 1
rText = "'NULL'"
sText = "('" & rst!CityID & "','" & rst!City & "','0')"
ReDim Preserve vResult(1 To n)
sText = Replace(sText, rText, "NULL")
vResult(n) = sText
'Print #1, LResult
rst.MoveNext
Loop
sText = Join(vResult, "," & vbCrLf) & ";"
Print #1, sText
rst.Close
Set rst = Nothing
t = ""
sText = ""
rText = ""
LResult = ""
Close #1
Exit_This_Sub:
Exit Sub
Err_Handler:
If Err = 0 Then
ElseIf Err = 94 Then
Resume Next
ElseIf Err = 3265 Then
Resume Next
Else
MsgBox "Error #: " & Err.Number & " " & Err.Description
End If
Resume Exit_This_Sub
End Sub
Please, try changing of this line:
sText = "('" & rst!CityID & "','" & rst!City & "','0'),"
with:
If rst.EOF then
sText = "('" & rst!CityID & "','" & rst!City & "','0');"
Else
sText = "('" & rst!CityID & "','" & rst!City & "','0'),"
End If

MSAccess login form

I created a login form but realized that i can log in without entering a password. only a user name. what should i do so as to solve the problem
Option Compare Database
Option Explicit
Private Sub cmdlogin_Click()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("Account Details", dbOpenSnapshot, dbReadOnly)
rs.FindFirst "UserName='" & Me.txtusername & "' "
Me.lblusername.Visible = False
If rs.NoMatch = True Then
Me.lblusername.Visible = True
Me.txtusername.SetFocus
Exit Sub
End If
Me.lblpassword.Visible = False
If rs!Password <> Me.txtpassword Then
Me.lblpassword.Visible = True
Me.txtpassword.SetFocus
Exit Sub
End If
DoCmd.OpenForm "Dashboard"
DoCmd.Close acForm, Me.Name
End Sub
If txtusername or txtpassword is Null the conditional will fail. Try:
rs.FindFirst "UserName='" & Nz(Me.txtusername,"") & "'"
If rs!Password <> Nz(Me.txtpassword, "") Then
Or consider:
Dim rs As Recordset
With Me
.lblusername.Visible = False
.lblpassword.Visible = False
If IsNull(.txtusername) Or IsNull(.txtpassword) Then
MsgBox "Enter username or password"
Else
Set rs = CurrentDb.OpenRecordset("SELECT UserName, Password FROM [Account Details] " & _
"WHERE UserName='" & .txtusername & "'", dbOpenSnapshot, dbReadOnly)
If Not rs.BOF And Not rs.EOF Then
If rs!Password <> .txtpassword Then
.lblpassword.Visible = True
.txtpassword.SetFocus
Else
DoCmd.OpenForm "Dashboard"
DoCmd.Close acForm, .Name
End If
Else
.lblusername.Visible = True
.txtusername.SetFocus
End If
End If
End With

Unable to add records more than 28 in access database

I am making my first project using vb.net and access. I am trying to develop a project in which the data of patients of the is added from different counters.it works fine till 22nd or 23rd record entered. after that adding new record over writes the last saved record.
to check the database i deleted some record (say after deletion there are 13 records left in the database) and tried to add new record, it gives the same problem, the 13th record is overwritten by the new record.
i deleted all the records and tried to add new record, the first record successfully entered but after that new record entry over writes the last (only) record.
i'm unable to understand the problem
code for saving data is
Private Sub Save()
'Dim st As String
Dim str As String
btnSave_Click = False
str = check
If Not str = "" Then
MsgBox(str, vbInformation, "Patient Registration")
btnSave_Click = False
Exit Sub
End If
If conn.State = 0 Then
Module1.openConnection()
End If
If Not rsDept Is Nothing Then
If rsDept.State = 0 Then
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
Else
Call openRecordset("SELECT * FROM tblDept", rsDept)
End If
If Not rsData Is Nothing Then
If rsData.State = 0 Then
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
Else
Call openRecordset("Select * from tblPatientRecord", rsData)
End If
conn.BeginTrans()
On Error GoTo ProcError
If Not (rsData.BOF And rsData.EOF) Then
rsData.MoveLast()
Call addData(rsData)
Else
Call addData(rsData)
End If
conn.CommitTrans()
MsgBox("Patient's Record Saved Successfully...!", MsgBoxStyle.Information, "Patient Registration")
Call loadDataListview()
Call fieldDisable()
Call Disable_SearchButtons()
btnSave_Click = True
comDepart.Enabled = False
conn.Close()
ProcError:
If Err.Number <> 0 Then
conn.RollbackTrans()
MsgBox(Err.Number & " " & Err.Description)
Call addNewR()
Exit Sub
End If
End Sub
Private Sub addData(rData As ADODB.Recordset)
Dim rsPaymentType As New ADODB.Recordset
'Dim str As String
If Not (rData.BOF And rsData.EOF) Then
rData.MoveFirst()
If rData.RecordCount > 0 Then
Do
If txthn.Text = rData("hNumber").Value Then
Call addVisit()
conn.Execute("update tblPatientRecord set visitNo = '" & vNo.Text & "' where hNumber = '" & txthn.Text & "'")
Call fieldEnable()
Exit Sub
End If
rData.MoveNext()
Loop Until rData.EOF
End If
End If
rData.AddNew()
rData("hNumber").Value = txthn.Text
rData("fName").Value = txtfn.Text
rData("contactNo").Value = txtContact.Text
rData("address").Value = txtaddress.Text
rData("cnic").Value = txtcnic.Text
'rData("cnic").Value = rCNIC()
rsData("visitNo").Value = vNo.Text
rsData("cnicSD").Value = comSD.Text
''Add gender as selected
If radmale.Checked = True Then
rData("gender").Value = radmale.Text
ElseIf radfemale.Checked = True Then
rData("gender").Value = radfemale.Text
Else
rData("gender").Value = " - "
End If
If txtAge.Text < 105 Or Year(dtAgePicker.Value) < 1915 Then
Call addAge()
'MsgBox("data of tblAge added")
Else
MsgBox("Please Enter Correct Age ", vbCritical, "")
txtAge.Select()
Exit Sub
End If
If comRelation.Text = "Select Relation with Patient" Or comRelation.Text = "" Then
comRelation.Text = "Not Selected"
End If
If txtfh.Text = "" Then
txtfh.Text = "Not Given"
End If
Call addRelation()
'Save Department ID as selected
If comDepart.Text <> "Select Department" Then
Call addVisit()
'MsgBox("data of tblVisit added")
Else
MsgBox("Please Enter the Department ", vbCritical, "")
comDepart.Select()
Exit Sub
End If
If Not rsPaymentType Is Nothing Then
If rsPaymentType.State = 0 Then
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open" & rsData.State)
End If
Else
Call openRecordset("Select * from tblPaymentType", rsPaymentType)
'MsgBox("Patient record is open")
End If
If Not (rsPaymentType.BOF And rsPaymentType.EOF) Then
rsPaymentType.MoveFirst()
Do
If rsPaymentType("paymentType").Value = comPaymentType.Text Then
rData("paymentType").Value = rsPaymentType("paymentTypeID").Value
Exit Do
Else
rData("paymentType").Value = 0
End If
rsPaymentType.MoveNext()
Loop Until rsPaymentType.EOF
End If
rsData.Update()
End Sub
Public Function h_N0_Generator(rs As ADODB.Recordset) As String
Dim str, p1() As String
Dim auto_long As Long
Dim hMonth As String
Dim strCounter As String, temp As String
'this counter file is added to make the hNumber unique for multiple counter /* in the file counter number is added and have respective counter number only*/
FileOpen(FileNum, "C048ounter.txt", OpenMode.Input)
strCounter = LineInput(FileNum)
FileClose(FileNum)
If strCounter = "" Then
strCounter = "1"
End If
hMonth = Month(Now).ToString("D2")
If (rs.EOF And rs.BOF) Then
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
Else
rs.MoveLast()
str = rs("HNumber").Value
p1 = str.Split("-")
' check if the current month is the same as in last stored Hospital No or not
'if yes the last five digits increment otherwise it restarts with 0
If p1(2) = Month(Now) And p1(1) = Year(Now) Then
temp = Right(rs(0).Value, 6)
auto_long = Left(temp, 5) + 1
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & Right("00000" & auto_long, 5) & strCounter
Else
h_N0_Generator = "NIRM-" & Year(Now) & "-" & hMonth & "-" & "00000" & strCounter
End If
End If
'Return auto_num
End Function

Scan image in vba with cannon scanner not work

I have a vba code that scan image from scanner , the code works and doesnt have any problem with type hp an brother scanner but when I used it with canon can not find the scanner and send message no wia device. How can solve this problem
Private Sub Command10_Click()
Const wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
On Error GoTo Handle_Err
Dim Dialog1 As New WIA.CommonDialog, DPI As Integer, PP As Integer, l As Integer
Dim Scanner As WIA.Device
Dim img As WIA.ImageFile
Dim intPages As Integer
Dim strFileJPG As String
Dim blnContScan As Boolean ' to activate the scanner to start scan
Dim ContScan As String 'msgbox to chk if more pages are to be scanned
Dim strFilePDF As String
Dim RptName As String
Dim strProcName As String
strProcName = "ScanDocs"
DoCmd.SetWarnings False
DoCmd.RunSQL "delete from scantemp"
DoCmd.SetWarnings False
blnContScan = True
intPages = 0
Do While blnContScan = True
DPI = 200
PP = 1 'No of pages
Set Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, True, False)
Set img = Dialog1.ShowTransfer(Scanner.Items(1), wiaFormatJPEG, True)
strFileJPG = ""
intPages = intPages + 1
strFileJPG = "\\User-pc\saveimage\" & num & Trim(str(intPages)) & ".jpg"
img.SaveFile (strFileJPG)
DoCmd.RunSQL "insert into scantemp (picture) values ('" & strFileJPG & "')"
DoCmd.SetWarnings False
Set Scanner = Nothing
Set img = Nothing
' strFileJPG = ""
'Prompt user if there are additional pages to scan
ContScan = MsgBox("?save another page ", vbQuestion + vbYesNoCancel)
If ContScan = vbNo Then
blnContScan = False
ElseIf ContScan = vbCancel Then
DoCmd.RunSQL "delete from scantemp where picture = '" & strFileJPG & "'"
End If
'''''''''''''''
Loop
Dim Image_Path As String
GoTo StartPDFConversion
StartPDFConversion:
Dim s As String
strFilePDF = "\\User-pc\saveimage\" & (num) & ".pdf"
RptName = "rptScan"
DoCmd.OpenReport RptName, acViewReport, , , acHidden
DoCmd.Close acReport, RptName, acSaveYes
DoCmd.OutputTo acOutputReport, RptName, acFormatPDF, strFilePDF
Me.imgp = strFilePDF
DoCmd.RunSQL "delete from scantemp" 'delete all data from table scantemp after converted it to pdf
'/*******************************\
'/********************************************\
Handle_Exit:
Exit Sub
Handle_Err:
Select Case Err.Number
Case 2501
Resume Handle_Exit
Case Else
MsgBox "the." & vbCrLf & vbCrLf & _
"In Function:" & vbTab & strProcName & vbCrLf & _
"Err Number: " & vbTab & Err.Number & vbCrLf & _
"Description: " & vbTab & Err.Description, 0, _
"Error in " & Chr$(34) & strProcName & Chr$(34)
Resume Handle_Exit
End Select
Exit Sub
End Sub
Option Compare Database
Private Declare Function TWAIN_AcquireToFilename Lib "TWAIN32d.DLL" (ByVal hwndApp As Long, ByVal bmpFileName As String) As Integer
Private Declare Function TWAIN_IsAvailable Lib "TWAIN32d.DLL" () As Long
Private Declare Function TWAIN_SelectImageSource Lib "TWAIN32d.DLL" (ByVal hwndApp As Long) As Long
Private Sub cmdScan_Click()
Dim Ret As Long, PictureFile As String
Dim intPages As Integer
Dim blnContScan As Boolean
Dim ContScan As String 'msgbox to chk if more pages are to be scanned
blnContScan = True
intPages = 0
Do While blnContScan = True
DPI = 200
PP = 1 'No of pages
intPages = intPages + 1
PictureFile = CurrentProject.Path & "\" & myfolder & "\" & Me.number & Trim(Str(intPages)) & ".jpg"
Ret = TWAIN_AcquireToFilename(Me.hwnd, PictureFile)
ContScan = MsgBox("? ÍÝÙ ÕæÑÉ ÇÎÑì ", vbQuestion + vbYesNo, "ÊäÈíÉ")
If ContScan = vbNo Then
blnContScan = False
End If
Loop

getting hyperlink from database to a sheet in excel

I am new to excel ..... well i have 2 excel sheets one as a database and another to display the result based on some selection
enter code here
//for database connectivity
Option Explicit
Public cnn As New ADODB.Connection
Public rs As New ADODB.Recordset
Public strSQL As String
Public Sub OpenDB()
If cnn.State = adStateOpen Then cnn.Close
cnn.ConnectionString =
"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
cnn.Open
End Sub
Public Sub closeRS()
If rs.State = adStateOpen Then rs.Close
rs.CursorLocation = adUseClient
End Sub
// code to display on another sheet
Private Sub cmdReset_Click()
'clear the data
ComboBox1.Clear
ComboBox2.Clear
ComboBox3.Clear
Sheets("View").Visible = True
Sheets("View").Select
Range("dataSet").Select
Range(Selection, Selection.End(xlDown)).ClearContents
End Sub
Private Sub cmdShowData_Click()
'populate data
strSQL = "SELECT * FROM [data$] WHERE "
If ComboBox1.Text <> "" Then
strSQL = strSQL & " [Product]='" & ComboBox1.Text & "'"
End If
If ComboBox2.Text <> "" Then
If ComboBox1.Text <> "" Then
strSQL = strSQL & " AND [Region]='" & ComboBox2.Text & "'"
Else
strSQL = strSQL & " [Region]='" & ComboBox2.Text & "'"
End If
End If
If ComboBox3.Text <> "" Then
If ComboBox1.Text <> "" Or ComboBox2.Text <> "" Then
strSQL = strSQL & " AND [Customer Type]='" & ComboBox3.Text & "'"
Else
strSQL = strSQL & " [Customer Type]='" & ComboBox3.Text & "'"
End If
End If
If ComboBox1.Text <> "" Or ComboBox2.Text <> "" Or ComboBox3.Text <> "" Then
'now extract data
closeRS
OpenDB
rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic
If rs.RecordCount > 0 Then
Sheets("View").Visible = True
Sheets("View").Select
Range("dataSet").Select
Range(Selection, Selection.End(xlDown)).ClearContents
'Now putting the data on the sheet
ActiveCell.CopyFromRecordset rs
Else
MsgBox"I was not able to find any matching records.",vbExclamation+ vbOKOnly
Exit Sub
End If
closeRS
OpenDB
rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic
If rs.RecordCount > 0 Then
Range("L6").CopyFromRecordset rs
Else
Range("L6:M7").Clear
MsgBox "There was some issue getting the totals.", vbExclamation + vbOKOnly
Exit Sub
End If
End If
End If
End Sub
Private Sub ComboBox1_DropButtonClick()
Dim v, e
With Sheets("data").Range("b2:b15")
v = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 1
For Each e In v
If Not .exists(e) Then .Add e, Nothing
Next
If .Count Then Me.ComboBox1.List = Application.Transpose(.keys)
End With
End Sub
Private Sub ComboBox2_DropButtonClick()
Dim v, e
With Sheets("data").Range("c2:c15")
v = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 1
For Each e In v
If Not .exists(e) Then .Add e, Nothing
Next
If .Count Then Me.ComboBox2.List = Application.Transpose(.keys)
End With
End Sub
Private Sub ComboBox3_DropButtonClick()
Dim v, e
With Sheets("data").Range("d2:d15")
v = .Value
End With
With CreateObject("scripting.dictionary")
.comparemode = 1
For Each e In v
If Not .exists(e) Then .Add e, Nothing
Next
If .Count Then Me.ComboBox3.List = Application.Transpose(.keys)
End With
End Sub
and snapshot to get better view
[displaying sheet][1] [1]: http://i.stack.imgur.com/pWBoJ.jpg
[input sheet with hyperlinks][2] [2]: http://i.stack.imgur.com/lYF3K.jpg
now the problem is I want to create a hyperlink on input sheet so that when the data is displayed in output sheet the hyperlink also displayed
also these 2 sheets are in same workbook
Thanks everyone in advance
edited after further explanation of OP about hyperlinks
as for your very question ("How to create a hyperlink on input sheet") you just have to copy web addresses from any source (web browser, list,...), paste them in your data sheet proper column and assure that "dataSet" range in "View" sheet is wide enough to enclose this column (from screenshots it would likely be some "Sheets("View").Range("A2:E2")")
besides that I must admit I didn't know about the existence of this ADODB connection (and many others, as now I got to know) to handle worksheet data. So I studied your code and came up to one of its possible refactorings that I hope you don't mind I'm posting here
Option Explicit
'they all seem like module level variables -> no need to declare them "Public"
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
' some more useful module level variables
Dim viewSht As Worksheet, dataSht As Worksheet
Dim dataSetRng As Range
Private Sub UserForm_Initialize()
'set module level variables -> they'll be used throughout this module by other subs/funcs
Set viewSht = Sheets("View")
Set dataSht = Sheets("Data")
Set dataSetRng = viewSht.Range("dataSet")
'fill comboboxes -> no need to fill them everytime you click a combobox
Call FillComboBox(Me.ComboBox1, dataSht.Range("b2:b15"))
Call FillComboBox(Me.ComboBox2, dataSht.Range("c2:c15"))
Call FillComboBox(Me.ComboBox3, dataSht.Range("d2:d15"))
viewSht.Activate '<<<== activate your view sheet once for all
End Sub
' code to display on another sheet
Private Sub cmdReset_Click()
Range(dataSetRng, dataSetRng.End(xlDown)).ClearContents
End Sub
Private Sub cmdShowData_Click()
Dim strSQL As String
'populate data
'build strSQL
Call SetStrSQL(strSQL, ComboBox1.text, "Product")
Call SetStrSQL(strSQL, ComboBox2.text, "Region")
Call SetStrSQL(strSQL, ComboBox3.text, "Customer Type")
'try and write data only if strSQL has been built
If Len(strSQL) >= 0 Then
strSQL = "SELECT * FROM [data$] WHERE " & strSQL
'now extract data
closeRS
OpenDB
rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic
If rs.RecordCount > 0 Then
With dataSetRng
Range(.Cells, .End(xlDown)).ClearContents
'Now putting the data on the sheet
.CopyFromRecordset rs
Call SetHyperLink(.CurrentRegion.Columns(5))
.EntireColumn.AutoFit
End With
Else
MsgBox "I was not able to find any matching records.", vbExclamation + vbOKOnly
Exit Sub
End If
closeRS
End If
End Sub
Public Sub SetHyperLink(rng As Range)
Dim cell As Range
For Each cell In rng.Offset(1).SpecialCells(xlCellTypeConstants)
rng.Parent.Hyperlinks.Add cell, cell.Value, , , cell.Value
Next cell
End Sub
Private Sub SetStrSQL(strSQL As String, cbText As String, field As String)
If cbText <> "" Then strSQL = strSQL & IIf(Len(strSQL) = 0, "", " AND") & " [" & field & "]='" & cbText & "'"
End Sub
Private Sub FillComboBox(Cb As ComboBox, dataRng As Range)
Dim v, e
v = dataRng.Value
With CreateObject("scripting.dictionary")
.CompareMode = 1
'instead of checking for every element in dictionary, it's faster to try and add element: duplicates will be automatically discharged
On Error Resume Next '<<< to prevent possible errors thrown by duplicates from stopping the macro
For Each e In v
.Add e, Nothing
Next
On Error GoTo 0 ' <<< enable error trapping
If .Count Then Cb.list = Application.Transpose(.Keys)
End With
End Sub
'-------------------------------
'-------------------------------
'ADODB handling code
' as for this block of code I'm just learning from you it exists
' I feel like it could be enhanced but don't know how
Private Sub OpenDB()
CloseDB
cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
cnn.Open
End Sub
Private Sub CloseDB()
If cnn.State = adStateOpen Then cnn.Close
End Sub
Private Sub closeRS()
If rs.State = adStateOpen Then rs.Close
rs.CursorLocation = adUseClient
End Sub
I see it gets visualized with quite strange an editing, but I don't know how to fix it!