Using VBA to get MDX Data - excel

I'm having a hard time getting results back in Excel connecting to an MDX database. Below is my code (I am incredibly new at this, so please be patient.) I did hijack someone's error code, so that part is not mine. The query runs through but I receive no data in Excel. Any help would be appreciated.
Sub Test()
Sheets("DataDump").Select
ActiveSheet.Range("A1").Value = "Department"
Set cn = New ADODB.Connection
cn.Open "provider=MSOLAP.3;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=XXX;Data Source=XXXXX;MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error"
Set rs = New ADODB.Recordset
strSQL = "select [product].[base color] on columns "
strSQL = strSQL & " From XXX "
strSQL = strSQL & " Where [Date].[Fiscal Week].&[2016]&[10] "
rs.Open strSQL, cn
Sheets("DataDump").Range("A2").CopyFromRecordset rs
rs.Close
Set rs = Nothing
Set Lists = Nothing
strSQL = vbNullString
StartDate = 0
EndDate = 0
SeasonYear = vbNullString
PriorYear = vbNullString
TXTYear = 0
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlCalculationAutomatic
.EnableEvents = True
.StatusBar = False
End With
Exit Sub
ErrorHandler:
Sheets("DataDump").Visible = xlVeryHidden
Set Lists = Nothing
strSQL = vbNullString
StartDate = 0
EndDate = 0
SeasonYear = vbNullString
PriorYear = vbNullString
TXTYear = 0
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlCalculationAutomatic
.EnableEvents = True
.StatusBar = False
End With
'Error Message
MsgBox "An Error occurred while retrieving data: " & Err.Description
End Sub

Here is an example of going straight to a cube via vba.
I've used this additional object ADOMD.Cellset to capture the results of the mdx.
Sub getFromCube()
Dim strConn As String
strConn = _
"Provider=MSOLAP.6;" & _
"Data Source=imxxxxxx;" & _ '<<<name of your server here
"Initial Catalog=AdventureWorksDW2012Multidimensional-EE;" & _ '<<<name of your Adv Wrks db here
"Integrated Security=SSPI"
Dim pubConn As ADODB.Connection
Set pubConn = New ADODB.Connection
pubConn.CommandTimeout = 0
pubConn.Open strConn
Dim cs As ADOMD.Cellset
Set cs = New ADOMD.Cellset
Dim myMdx As String
myMdx = _
" SELECT" & _
" NON EMPTY" & _
" [Customer].[Customer Geography].[State-Province].&[AB]&[CA] ON 0," & _
" NON EMPTY" & _
" [Measures].[Internet Sales Amount] ON 1" & _
" FROM [Adventure Works];"
With cs
.Open myMdx, pubConn
ActiveSheet.Range("A1") = cs(0, 0)
.Close
End With
End Sub

Related

Check a value in another closed workbook

I have an excel file and name (Test 1) in the same folder path.
And it has a value on ("Sheet1") in the range "C3".
And I want to check this value without ever opening the workbook.
Sub Check()
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Dim mydata As String
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\test1.xlsx")
If wb.Worksheets("Sheet1").Range("C3").Value = "a9a" <> Empty Then
MsgBox "The value is correct", 64
Else
myError:
MsgBox "The value is incorrect", 64
End If
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
End Sub
You can quickly read data from another workbook without opening it, using ADO (see https://learn.microsoft.com/en-us/previous-versions/office/troubleshoot/office-developer/transfer-excel-data-from-ado-recordset). Working sample:
Option Explicit
Sub Check()
Dim con As Object, rst As Object, tFilePath As String
Set rst = CreateObject("ADODB.Recordset")
Set con = CreateObject("ADODB.Connection")
tFilePath = ThisWorkbook.Path & "\test1.xlsx"
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & tFilePath & ";" & _
"Extended Properties='Excel 12.0;HDR=NO';"
rst.Open "SELECT * FROM [Sheet1$C3:C3]", con, 3, 1
If rst.Fields(0).Value = "a9a" Then
MsgBox "The value is correct", 64
Else
MsgBox "The value is incorrect", 64
End If
rst.Close: Set rst = Nothing
con.Close: Set con = Nothing
End Sub

Visual Basic For Applications " subscript out of range" error

" I am getting a subscript out of range error after adding two new elements to an array. I remove the elements and re-run the code and it works. I need to know where to change the range so that it accommodates the array elements. This is the edited code: products = Array("BALANCER", "SKIN LIGHTENER", "FIRM AND FADE 6%", "FIRM AND FADE 8%")
After adding the two additional elements the error is thrown.
Research is showing that the array is the issue however after making adjustments the error message is still being thrown. "
"Here is the original code:"
Public Sub Dermesse_Dashboard(SD As Date, ED As Date)
Dim cn As ADODB.Connection
Dim rs As ADODB.RecordSet
Dim com As ADODB.Command
Dim ConnectionString As String, StoredProcName As String
Dim StartDate As ADODB.Parameter, EndDate As ADODB.Parameter, Product As ADODB.Parameter
Dim excelrange As String
Dim DateRange As String
Dim RCount As Integer
Dim products As Variant
products = Array("BALANCER", "SKIN LIGHTENER")
Set cn = New ADODB.Connection
Set rs = New ADODB.RecordSet
Set com = New ADODB.Command
Workbooks.Open ("\\apfssvr01\Arrow_RX\Reports\Templates\Dermesse_Dashboard(Template).xlsx")
ConnectionString = "Provider=sqloledb;Data Source=ARWSQL01;initial catalog=futurefill;User Id=endicia;Pwd=endicia;trusted_connection=yes;"
On Error GoTo CloseConnection
Application.ScreenUpdating = False
cn.Open ConnectionString
cn.CursorLocation = adUseClient
StoredProcName = "Dermesse_Shipped_by_Product"
With com
.ActiveConnection = cn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
Set StartDate = com.CreateParameter("#StartDate", adDBTimeStamp, adParamInput, , SD)
com.Parameters.Append StartDate
Set EndDate = com.CreateParameter("#Enddate", adDBTimeStamp, adParamInput, , ED)
com.Parameters.Append EndDate
ActiveWorkbook.Sheets(2).Select
'loop through each item in products.
For Each i In products
'remove the product parameter if it exists so we can set it to the next product
If Product Is Nothing = False Then
com.Parameters.Delete (2)
End If
Set Product = com.CreateParameter("#Product", adVarChar, adParamInput, 200, i)
com.Parameters.Append Product
Set rs = com.Execute
'add rows to the excel table if the record set if 2 or greater.
'if we dont any tables below the first could be over written
If rs.RecordCount >= 2 Then
For j = 0 To rs.RecordCount - 3
ActiveSheet.ListObjects("Ship " & i).ListRows.Add (2)
Next
End If
ActiveSheet.ListObjects("Ship " & i).DataBodyRange.Select
Selection.CopyFromRecordset rs
rs.Close
Next
ActiveWorkbook.Sheets(6).Select
StoredProcName = "Dermesse_Shipped_wOrder"
With com
.ActiveConnection = cn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
If Product Is Nothing = False Then
com.Parameters.Delete (2)
End If
Set Product = com.CreateParameter("#Product", adVarChar, adParamInput, 200, "Dermesse")
com.Parameters.Append Product
Set rs = com.Execute
RCount = rs.RecordCount
With ActiveSheet.ListObjects("Invoice DERMESSE")
If rs.RecordCount >= 2 Then
For j = 0 To rs.RecordCount - 3
.ListRows.Add (2)
Next
End If
.DataBodyRange.Select
Selection.CopyFromRecordset rs
.ListColumns(12).Range.Select
Selection.NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(#_)"
End With
rs.Close
cn.Close
'set a data fee value for each record. look at the order number of a specific line. if the line above or below are the same
'the data fee is 7.5 else is 10
r = 9
For i = 0 To RCount - 1
If ActiveSheet.Range("C" & r + i).Value = ActiveSheet.Range("C" & (r + i) - 1).Value Then
ActiveSheet.Cells(r + i, 12).Value = 7.5
ElseIf ActiveSheet.Range("C" & r + i).Value = ActiveSheet.Range("C" & (r + i) + 1).Value Then
ActiveSheet.Cells(r + i, 12).Value = 7.5
Else
ActiveSheet.Cells(r + i, 12).Value = 10
End If
Next i
If SD <> ED Then
DateRange = Format(SD, "yyyy-mm-dd") & " through " & Format(ED, "yyyy-mm-dd")
Else
DateRange = Format(SD, "yyyy-mm-dd")
End If
With ActiveWorkbook
For i = 1 To .Sheets.Count
.Sheets(i).Select
.Sheets(i).Range("A2").Value = DateRange
Next
.Sheets("Dermesse Dashboard").Select
End With
On Error GoTo 0
Application.DisplayAlerts = False
ActiveWorkbook.RefreshAll
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs ("\\apfssvr01\Arrow_RX\Reports\Dermesse\DERMESSE_Dashboard(" & DateRange & ").xlsx"), FileFormat:=51
Application.DisplayAlerts = True
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
frmSwitchboard.lblDD.Caption = "Report Complete"
Exit Sub
CloseConnection:
Application.ScreenUpdating = True
frmSwitchboard.lblDD.Caption = "Error: " & Error
cn.Close
If ActiveWorkbook.Sheets(1).Name <> "Sheet1" Then
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End If
End Sub
Any help would be greatly appreciated

Load aggregate data from Excel into ADODB.RecordSet

I am trying to load data from an Excel file in a specific sheet into an ADODB.RecordSet via a VBA macro by using SQL SELECT command.
There are several columns on the Excel sheet, and I don't need all of them.
For example:
col.A = Surname, col.B = Name, col.C = IDPerson, [....columns that are not needed], Col.N = Boss
The purpose would be to get a recordset of aggregated data for:
col.C = IDPerson, col.N = Boss.
The fields highlighted in the image below.
I would like to have a RecordSet with the aggregated (non-repeating) data of the columns highlighted in yellow.
Obviously, this problem could also be solved by loading a matrix, but, in this case I would have to build a loading algorithm to "clean" any repetitions in the data and then later I would have to provide a search function with some loops.
So I thought that if I could load all the data I need by reading the WorkSheet as if it were a data table and then make a query on it to extract the data that I need and load everything in an ADODB.RecordSet would be much more efficient also for searching for data (filter data for example).
Below I report my code that loads all the data of my sheet:
Public Sub LoadRecordSet(ByVal LastRow As Long, ByVal LastCol As Integer)
Dim cnt As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
strTMP = Cells(LastRow, LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
strSQL = "SELECT * FROM [Sheet1$C2:" & strTMP & "]"
Set rsData = New ADODB.Recordset
With rsData
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
'TODO - Something with rsData for filtering or to research
'GC
If Not rsData Is Nothing Then
If rsData.State <> adStateClosed Then rsData.Close
Set rsData = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
End Sub
My question is: "What if I just want to load some columns as described above and aggregate them so they don't have repetitions in the data?"
For example if I want to load similar
SELECT [cod.fiscale], responsabile FROM [MySheet$A3:N480] GROUP BY [cod.fiscale], responsabile
It's possible?
Thank you so much.
I improved my code which is now working:
Public Sub CaricaDati()
Dim cnt As ADODB.Connection
Dim rsDati As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
Dim i As Integer
on Error GoTo Error_Handler
Range("A3").Select
g_BOLTS_UltimaRiga = LasRow
Call LastCol
strTMP = Cells(g_LastRow, g_LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
'strSQL = "SELECT * FROM [2$C2:" & strTMP & "]"
strSQL = "SELECT cf, responsabile FROM [2$C2:" & strTMP & "] GROUP BY cf, responsabile"
Set rsDati = New ADODB.Recordset
With rsDati
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
If Not (rsDati.BOF And rsDati.EOF) Then
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Name & ";"
Next i
Debug.Print strTMP
strTMP = ""
rsDati.MoveFirst
Do While Not rsDati.EOF
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Value & ";"
Next i
Debug.Print strTMP
rsDati.MoveNext
Loop
End If
Uscita:
On Error Resume Next
'GC
If Not rsDati Is Nothing Then
If rsDati.State <> adStateClosed Then rsDati.Close
Set rsDati = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
Exit Sub
Error_Handler:
On Error GoTo 0
MsgBox Err.Number & " - " & Err.Description, vbOKOnly + vbCritical, "ERRORE IMPREVISTO"
GoTo Uscita
End Sub

Incorrect syntax near '>>'. Excel VBA reads .SQL file with funny leading characters (i.e.  select top 100 * from test). Encoding issue

I am having trouble with this VBA script and it seems to keep adding funny characters (i.e.) every time it reads the .SQL file. I believe this is due to encoding.
Option Explicit
Sub SomeExtract()
With Application
.ScreenUpdating = False: .DisplayAlerts = False: .Calculation = xlCalculationManual: .EnableEvents = False
End With
Dim strSQL As String, filePath As String, fileSQL As Integer, row As String
Dim connSQL As ADODB.Connection, serverName As String, databaseName As String, userID As String, userPassword As String, rs As ADODB.Recordset
fileSQL = FreeFile
strSQL = ""
filePath = Application.ThisWorkbook.Path & "\somesql.sql"
Open filePath For Input As fileSQL
Do Until EOF(fileSQL)
Line Input #fileSQL, row
strSQL = strSQL & row & vbNewLine
Loop
Close #fileSQL
serverName = "someserver"
databaseName = "somedb"
Set connSQL = New ADODB.Connection
Set rs = New ADODB.Recordset
connSQL.Open "Provider=SQLOLEDB;Server=" & serverName & ";Database=" & databaseName & _
";Trusted_connection=yes;"
rs.Open strSQL, connSQL, adOpenStatic
With ThisWorkbook.Sheets("test").Range("A1:Z1000000")
.ClearContents
.CopyFromRecordset rs
End With
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .Calculation = xlCalculationAutomatic: .EnableEvents = True
End With
ExitPoint:
With Application
.ScreenUpdating = True: .DisplayAlerts = True: .Calculation =
xlCalculationAutomatic: .EnableEvents = True
End With
Set rs = Nothing
Exit Sub
ErrHandler:
With ThisWorkbook
.Sheets("Control").Range("B1").Value = Err.Description
.Sheets("Control").Range("C1").Value = strSQL
End With
Resume ExitPoint
End Sub
The error message says "Run-time error '-2147217900 (80040e14)': Incorrect syntax near '>>';". The SQL file doesn't have >> or any other characters as shown on the error message. In fact, I have replaced the .sql to only contain a straight SELECT statement. But I still seeing the funny characters being added when it is being read by Excel VBA (e.g. select top 100 * from test" instead of "select top 100 * from test").

MS Excel not updating with Access database. VB6

I have created a form in which when I click a button(subMnuPrintStaff), it should open an Excel file(WorkerNames.xls). The Excel file gets its records from my database(Employee.mdb). However, the problem is that when I update my databasefile(Employee.mdb), the records on my Excel file does not get updated. How do I fix this?
I am using flexgrid.
BUTTON CODE:
Private Sub subMnuPrintStaff_Click()
'On Error GoTo er
Dim oExcel As Object
Set oExcel = CreateObject("Excel.Application")
Dim oWorkBook As Object
Dim oWorkSheet As Object
Dim i As Integer, k As Integer
Dim lRow As Long
Dim LastRow As Long
Dim LastCol As Long
oExcel.Visible = False
oExcel.Workbooks.Open App.Path & "\WorkerNames.xls"
Set oWorkSheet = oExcel.Workbooks("WorkerNames.xls").Sheets("WorkerNames")
i = 2 'Row in Excel
LastRow = DataGrid1.Row 'Save Current row
LastCol = DataGrid1.Col 'and column
DataGrid1.Row = 0 'Fixed Row is -1
Do While DataGrid1.Row <= DataGrid1.VisibleRows - 1
For k = 1 To DataGrid1.Columns.Count - 1
DataGrid1.Col = k 'Fixed Column is -1
oWorkSheet.Cells(i, k).Font.Bold = False
oWorkSheet.Cells(i, k).Font.Color = vbBlack
oWorkSheet.Cells(i, k).Value = DataGrid1.Text
Next
i = i + 1
If DataGrid1.Row < DataGrid1.VisibleRows - 1 Then
DataGrid1.Row = DataGrid1.Row + 1
Else
Exit Do
End If
Loop
DataGrid1.Row = LastRow 'Restore original Row
DataGrid1.Col = LastCol 'and Column
oExcel.Workbooks("WorkerNames.xls").Save
oExcel.Workbooks("WorkerNames.xls").Close savechanges:=True
oExcel.Quit
'cmdView.Enabled = True
'er:
'If err.Number = 1004 Then
'Exit Sub
'End If
On Error GoTo ErrHandler
Dim xlApp As Object
Dim xlWB As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open("WorkerNames.xls")
Exit Sub
ErrHandler:
MsgBox "There is a problem opening that workbook!", vbCritical, "Error!"
End Sub
FORM LOAD CODE:
Dim oRs As New ADODB.Recordset
Dim adoConn2 As ADODB.Connection
Set adoConn2 = New ADODB.Connection
adoConn2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " & App.Path & "\Employee.mdb"
adoConn2.Open
oRs.CursorLocation = adUseClient
oRs.Open "select * from employeeName", adoConn2, adOpenKeyset, adLockPessimistic
Set DataGrid1.DataSource = oRs
DataGrid1.Refresh
Any help would be greatly appreciated. Database and Excel files are in the same directory with the project.
CODE FOR SAVING DATA INTO MY DATABASE - using text boxes
Dim adoConn As New ADODB.Connection Dim constr, curSql As String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & App.Path & "\employee.mdb;Persist Security Info=False"
Set adoConn = New ADODB.Connection
adoConn.ConnectionString = constr adoConn.Open
If txtFirstName.Text = "" Or txtLastName.Text = "" Then
MsgBox "Some fields are empty!", vbInformation + vbOKOnly, "Empty Fields"
Else curSql = "INSERT INTO employeename(Firstname, LastName) VALUES ("curSql = curSql & "'" & Replace(txtFirstName.Text, "'", "''") & "'," curSql = curSql & "'" & Replace(txtLastName.Text, "'", "''") & "')"
adoConn.Execute curSql
adoConn.Close
MsgBox "Data successfully added!", vbOKOnly, "Success!"
txtFirstName.Text = ""
txtLastName.Text = ""

Resources