Inserting excel sheet in Existing table in Access - excel

I am pretty New to VBA, In here i my tring to insert some data from the excel sheet looping through each and, in Access existing, the code runs fine but doesn't insert any data in the table, i aslo try appending that data using recordset, but did work because of the data type issue. Please guide me through it, Thank you very much in Advance.
This is My Code:
Const AccessConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\Documents and Settings\e4umts\Desktop\New Database\IRG Analytics--New.accdb;Persist Security Info=False"
Sub Import()
Dim dbsIRG As ADODB.Connection
Dim ConnectionString As String
Dim IRGConn As ADODB.Connection
Dim Mypath As String
Dim IRGCmd As New ADODB.Command
Dim r As Range
Dim column As Integer
Dim row As Integer
Mypath = "C:\Documents and Settings\e4umts\Desktop\New Folder\Liquidation Exceptions Report.xls"
Set IRGConn = New ADODB.Connection
IRGConn.ConnectionString = AccessConnectionString
IRGConn.Open
Set IRGCmd = New ADODB.Command
IRGCmd.ActiveConnection = IRGConn
For Each r In ActiveSheet.Range("A2", Range("A2").End(xlDown))
If ActiveSheet.Range("A2", Range("A2").End(xlDown)) Is Nothing Then
IRGCmd.CommandText = _
GetSQL( _
r.Offset(0, 0).Value, _
r.Offset(0, 1).Value, _
r.Offset(0, 2).Value, _
r.Offset(0, 3).Value, _
r.Offset(0, 4).Value, _
r.Offset(0, 5).Value, _
r.Offset(0, 6).Value, _
r.Offset(0, 7).Value, _
r.Offset(0, 8).Value, _
r.Offset(0, 9).Value, _
r.Offset(0, 10).Value, _
r.Offset(0, 11).Value, _
r.Offset(0, 12).Value, _
r.Offset(0, 13).Value, _
r.Offset(0, 14).Value, _
r.Offset(0, 15).Value, _
r.Offset(0, 16).Value, _
r.Offset(0, 17).Value, _
r.Offset(0, 18).Value, _
r.Offset(0, 19).Value, _
r.Offset(0, 20).Value, _
r.Offset(0, 21).Value, _
r.Offset(0, 22).Value)
ActiveSheet.Range("A2", Range("A2").End(xlDown)).Value = ""
IRGCmd.Execute
Else
End If
Next r
IRGConn.Close
Set IRGConn = Nothing
End Sub
Function GetSQL(LoanNumber As Integer, Manager As String, Analyst As String, _
ServicerName As String, ServicerNumber As Integer, ServicerLoanNumber As Integer, _
PoolNumber As Integer, RemmittanceType As String, SaleType As String, ActionCode As Integer, _
ActivityDate As Date, ActionDate As Date, LPI As Date, InterestRate As Double, PandI As Double, _
UPB As Double, ReportedPrincipal As Double, ReportedInterest As Double, AppliedPrincipal As Double, _
AppliedInterest As Double, InvestorPassThruRate As Double, PFPIntAdv As Double, Months As Date) As String
Dim strSql As String
strSql = _
" INSERT INTO Table1" & _
" (LoanNumber, Manager, Analyst, ServicerName, ServicerNumber, ServicerLoanNumber," & _
" PoolNumber, RemittanceType, SaleType, ActionCode, ActivityDate, ActionDate, LPI, InterestRate," & _
" PandI, UPB, ReportedPrincipal, ReportedInterest, AppliedPrincipal, AppliedInterest, InvestorPassThruRate, PFPIntAdv, Months )" & _
" VALUES (" & _
" Cstr'FannieMaeLoanNumber'),'" & Manager & "','" & Analyst & "','" & ServicerName & "'," & _
" Cstr('ServicerNumber'),Cstr('ServicerLoanNumber'), Cstr('PoolNumber'), '" & RemmittanceType & "'" & _
" '" & SaleType & "', Cstr('ActionCode'), #" & ActivityDate & "#, #" & ActionDate & "#,#" & LPI & "#,Cstr('InterestRate')," & _
" Cstr('PandI'),Cstr('UPB'),Cstr('ReportedPrincipal'),Cstr('ReportedInterest'),Cstr('AppliedPrincipal'),Cstr('AppliedInterest'),Cstr('InvestorPassThruRate')," & _
" Cstr('PFPIntAdv'),#" & Months & "#)"
GetSQL = strSql
End Function

Thank you very much for your reply, i went the code that you have posted by what i really dont undertand is i don't see any file xl file path, i have to insert data in into the table every month, and the xlfile is saved in specific folder,given static Name, what i do is first i rewrite the field name on excel via vba to match with my table field name in access,where i activate the xlfile , after that i am trying to import. Since i am working on the access it self i dont think i have to give a string for database connection.I am really confused here It would be very great full if you could explain it more for me.
Thank you
Manoj

Related

Filter fields in Tableau and download filtered files with VBA code

I want to write a code in Vba that when I click a button in Excel data, then in Tableau the fields are filled according to my Excel data and then the final filtered file is downloaded from Tableau. I have written this code but I get an empty Excel:
Sub GetSizeDataFromTableau(Optional strType As String = "")
Dim strLink As String
Dim wshshell As Object
With ThisWorkbook.Worksheets("Ordersheet")
If .Cells(1, 4) <> "" And .Cells(2, 4) <> "" And .Cells(2, 3) <> "" And .Cells(4, 43) <> "" Then 'Master Brand / Saison / Categorie 1 / Typ Produkttyp oder Categorie 2
strLink = "http://mymind.mytoys.group/#/views/ArticleSizeDistribution/Articlesizedistribution2" & strType & "?" & _
"&Switch off Target Grp/Gender on/off=on" & _
"&Purchase Department=PMM" & _
"&End Order Date (Transaction)=" & Year(Date) & "-" & Month(Date) & "-" & Day(Date) & _
"&order quantity=100" & _
"&Parameter.Category 1=" & .Cells(2, 3) & _
"&Parameter.Master Brand=" & .Cells(1, 4)
'Size data level
If UCase(.Cells(4, 43)) = "PT" Then
strLink = strLink & "&Switch between Dimensions=Product Type"
Else
strLink = strLink & "&Switch between Dimensions=Category 2"
End If
'Start Order Date
If Left(.Cells(2, 4), 2) = "FS" Then
strLink = strLink & "&Start Order Date (Transaction)=" & "20" & Right(.Cells(2, 4), 2) - 1 & "-01-01"
Else
strLink = strLink & "&Start Order Date (Transaction)=" & "20" & Right(.Cells(2, 4), 2) - 1 & "-07-01"
End If
'Supplier
If .Cells(1, 3) <> "" Then
strLink = strLink & "&Parameter.Primary Supplier=" & .Cells(1, 3)
End If
strLink = Replace(strLink, " ", "%20")
Set wshshell = CreateObject("WScript.Shell")
wshshell.Run strLink
If strType <> "" Then
.OLEObjects("cmdGetSizeData").Object.BackColor = RGB(0, 255, 0)
End If
Else
MsgBox "the following fields must be specified so that the size distribution data can be pulled from Tableau:" & vbNewLine & _
" - Size data level" & vbNewLine & _
" - Saison" & vbNewLine & _
" - Category 1" & vbNewLine & _
" - Marke" & vbNewLine & _
" Optional: Supplier"
End If
End With
End Sub

cmd.transferspreadsheet is sending old excel data to access

I am using cmd.transferspreadsheet in Excel VBA to import an Excel sheet into an Access Table. Every time I run this code, the data sent to access is 1 iteration out of date. I have zeroed in on two columns one that has a tier assignment (column 4) and one that has a string for the time and person who is submitting (column 13). In stepping through the code, I am printing the values of these 2 columns to the immediate window. I am doing that both by a range reference and an object reference. Both give me the correct answer, but when I go into Access, I see the data that was there before I changed it. What am I doing wrong?!?!?!
Sub SendTiersToDB()
'sends the data from this file to the access database
Dim fPathName As String
Dim dbTblTiers As String
Dim strSubmit As String
Dim tblXLTiers As ListObject
Dim strXLTiers As String
Dim appDB As New Access.Application
Set tblXLTiers = Sheet7.ListObjects(1)
fPathName = "\\MERCH\Assortment Planning\Databases\New_AP_Database.accdb"
strXLTiers = tblXLTiers.DataBodyRange.Address
dbTblTiers = "Tbl_Tiers"
'Fill In Subbmission Data
strSubmit = "Last Submitted: " & Now & " by " & Environ("username")
tblXLTiers.ListColumns(13).DataBodyRange.Value = strSubmit
tblXLTiers.ListColumns(13).DataBodyRange.Calculate
'and insert the new store records
Debug.Print "By Range " & Sheet7.Range("D2").Value
Debug.Print "By Range " & Sheet7.Range("M2").Value
Debug.Print "By Object " & tblXLTiers.DataBodyRange(1, 4)
Debug.Print "By Object " & tblXLTiers.DataBodyRange(1, 13)
appDB.OpenCurrentDatabase fPathName
appDB.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=dbTblTiers, _
Filename:="https://theexcelfilepath/file.xlsb", _
HasFieldNames:=True, _
Range:=Sheet7.Name & "$" & "A1:O9277"
End Sub
Thank you for the comments! I woke up at 4AM with the same thought.
I added a line to save the file prior to the DoCmd line, and that did the trick!
'Fill In Subbmission Data
strSubmit = "Last Submitted: " & Now & " by " & Environ("username")
tblXLTiers.ListColumns(13).DataBodyRange.Value = strSubmit
tblXLTiers.ListColumns(13).DataBodyRange.Calculate
ThisWorkbook.Save
'and insert the new store records
appDB.OpenCurrentDatabase fPathName
appDB.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=dbTblTiers, _
Filename:="https://theexcelfilepath/file.xlsb", _
HasFieldNames:=True, _
Range:=Sheet7.Name & "$" & "A1:O9277"

VBA - encoding, .csv format and separators' change

I need to create a script which saves active sheet in .csv, using UTF-8 encoding and changes separators. I'm totally new in VBA thing so I've found here some useful code. The one thing that is missing is encoding. I tried to do it by myself without success.
Sub Zapisz_Arkusz_Jako_CSV()
'wg http://www.mcgimpsey.com/excel/textfiles.html
Const myListSeparator As String = ";"
Const myDecimalSeparator As String = "."
Const myDateFormat As String = "yyyy-mm-dd"
Dim Path As String
Dim nFileNum As Long
Dim myRecord As Range
Dim myField As Range
Dim myFieldText As String
Dim sOut As String
Path = Left(ActiveWorkbook.FullName, _
InStr(ActiveWorkbook.FullName, ".") - 1) & _
"_" & ActiveSheet.Name & ".csv"
If MsgBox("Arkusz zostanie zapisany jako: " & _
vbNewLine & vbNewLine & Path, vbOKCancel, _
" Zapisywanie aktywnego arkusza") = vbOK Then
nFileNum = FreeFile
Open Path For Output As #nFileNum
For Each myRecord In Range("A1:A" & _
Range("A" & Rows.Count).End(xlUp).Row)
With myRecord
For Each myField In Range(.Cells, _
Cells(.Row, Columns.Count).End(xlToLeft))
Select Case TypeName(myField.Value)
Case "Date"
myFieldText = Format(myField.Value, myDateFormat)
Case "Double", "Currency"
myFieldText = WorksheetFunction.Substitute( _
myField.Text, _
Application.DecimalSeparator, _
myDecimalSeparator)
Case Else
myFieldText = myField.Text
End Select
sOut = sOut & myListSeparator & myFieldText
Next myField
Print #nFileNum, Mid(sOut, 2)
sOut = Empty
End With
Output.Charset = "utf-8"
Next myRecord
Close #nFileNum
End If
End Sub
This one shows me information that for .Charset i need an object. So where is the proper place for it? Or maybe should I do it other way?
Thank you in advance :)
Here is your code according to this post
Sub Zapisz_Arkusz_Jako_CSV()
'wg http://www.mcgimpsey.com/excel/textfiles.html
Const myListSeparator As String = ";"
Const myDecimalSeparator As String = "."
Const myDateFormat As String = "yyyy-mm-dd"
Dim Path As String
Dim nFileNum As Long
Dim myRecord As Range
Dim myField As Range
Dim myFieldText As String
Dim sOut As String
Path = Left(ActiveWorkbook.FullName, _
InStr(ActiveWorkbook.FullName, ".") - 1) & _
"_" & ActiveSheet.Name & ".csv"
If MsgBox("Arkusz zostanie zapisany jako: " & _
vbNewLine & vbNewLine & Path, vbOKCancel, _
" Zapisywanie aktywnego arkusza") = vbOK Then
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
For Each myRecord In Range("A1:A" & _
Range("A" & Rows.Count).End(xlUp).Row)
With myRecord
For Each myField In Range(.Cells, _
Cells(.Row, Columns.Count).End(xlToLeft))
Select Case TypeName(myField.Value)
Case "Date"
myFieldText = Format(myField.Value, myDateFormat)
Case "Double", "Currency"
myFieldText = WorksheetFunction.Substitute( _
myField.Text, _
Application.DecimalSeparator, _
myDecimalSeparator)
Case Else
myFieldText = myField.Text
End Select
sOut = sOut & myListSeparator & myFieldText
Next myField
fsT.WriteText Mid(sOut, 2) & vbCrLf
sOut = Empty
End With
Next myRecord
fsT.SaveToFile Path, 2 'Save binary data To disk
fsT.Flush
fsT.Close
End If
End Sub

Embed a Google Street View image into Excel

I'm trying to embed a Google Street View into Excel. I found this link which has the below code. Doesn't really work at all for me, and looking for some help to get started. Clearly I need to set up variables for the lookups of the URL of street view. But I've never inserted an image through VBA, looking for some guidance.
Sub GoogleStaticStreetView(oShape As Shape, _
sAddress As String, _
lHeading As Long, _
Optional lHeight As Long = 512, _
Optional lWidth As Long = 512)
'https://developers.google.com/maps/documentation/streetview/
Dim sURL As String
Dim sMapsURL As String
On Error GoTo RETURN_FALSE
If bRunMode Then On Error Resume Next 'Error if quota exceeded
If Len(sAddress) > 0 Then
'URL-Escaped addresses
sAddress = Replace(sAddress, " ", "+")
Else
Exit Sub
End If
sURL = _
"http://maps.googleapis.com/maps/api/streetview?" & _
"&location=" & sAddress & _
"&size=" & lWidth & "x" & lHeight & _
"&heading=" & lHeading & _
"&sensor=false"
sMapsURL = "http://maps.google.com/maps?q=" & _
sAddress & "&t=m&layer=c&panoid=0" & _
"&cbp=12," & lHeading & ",,0,4.18"
oShape.Fill.UserPicture sURL
oShape.AlternativeText = sMapsURL
Exit Sub
RETURN_FALSE:
End Sub
Sub GoogleStaticMap(oShape As Shape, _
sAddress As String, _
Optional sMapType As String = "roadmap", _
Optional lZoom As Long = 12, _
Optional lHeight As Long = 512, _
Optional lWidth As Long = 512)
'https://developers.google.com/maps/documentation/staticmaps/
Dim sURL As String
Dim sMapsURL As String
Dim sMapTypeURL As String
On Error GoTo RETURN_FALSE
' Google Maps Parameters '&t=m' = roadmap, '&t=k' = satellite
sMapTypeURL = "m"
If sMapType = "satellite" Then
sMapTypeURL = "k"
End If
If bRunMode Then On Error Resume Next 'Error if quota exceeded
If Len(sAddress) > 0 Then
'URL-Escaped addresses
sAddress = Replace(sAddress, " ", "+")
Else
Exit Sub
End If
sURL = _
"http://maps.googleapis.com/maps/api/staticmap?center=" & _
sAddress & "," & _
"&maptype=" & sMapType & _
"&markers=color:green%7Clabel:%7C" & sAddress & _
"&zoom=" & lZoom & _
"&size=" & lWidth & "x" & lHeight & _
"&sensor=false" & _
"&scale=1"
sMapsURL = "http://maps.google.com/maps?q=" & _
sAddress & _
"&z=" & lZoom & _
"&t=" & sMapTypeURL
oShape.Fill.UserPicture sURL
oShape.AlternativeText = sMapsURL
Exit Sub
RETURN_FALSE:
End Sub
You can get that code to work by adding this line to the other Dims in GoogleStaticStreetView:
Dim bRunMode As Boolean
Then running this module:
Sub makeThisCodeWork()
GoogleStaticStreetView Sheets(1).Shapes.AddShape(msoShapeRectangle, 0, 0, 512, 512), "GooglePlex, CA 94043", 100
Debug.Assert False
Sheets(1).Shapes.Delete
End Sub
This just creates a rectangle shape object to use as a container, then it lets the code paste the image in.
It will pause execution when it gets to debug.assert false, and then it will delete all shapes on the sheet so you can clean run it again. You'll have to play with the address and the heading variables to get what you want though.
I didn't try to run the other module, because that is for returning maps, and you just said StreetView :)
Hope this helps - let me know if you want me to be more verbose/explain what is going on here.

Run-time error 5 in excel while saving a word document as a pdf

So I've been running this code on a couple computers for awhile. However, the spreadsheet has begun to crash and refuses to save, so I created a new one, with everything the same. It crashes as I try and save my word document as a PDF, specifically, this line
wrdDoc.ExportAsFixedFormat OutputFileName:=Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
Here is my full code, My apologies for lack of comments etc, it was written to be used only by me.
Sub AutoFill()
ScreenUpdating = False
Dim Job As String
Dim Rail As String
Dim Panel_Type As String
Dim Address As String
Dim Lot_Number As Integer
Dim Suburb As String
Dim Town As String
Dim Town_Check As String
Dim Current_Date As String
Dim DTC As String
Dim WordFileName As String
Dim Path As String
Dim i As Integer
Dim wrdApp As Object
Dim wrdDoc As Object
Dim count As Integer
count = Range("Solarcount")
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
wrdApp.DisplayAlerts = wdAlertsNone
For i = 1 To count
Job = Range("WordArray").Cells(i, 1)
Rail = Range("WordArray").Cells(i, 2)
Panel_Type = Range("WordArray").Cells(i, 3)
Lot_Number = Range("WordArray").Cells(i, 4)
Suburb = Range("WordArray").Cells(i, 7)
Address = Range("WordArray").Cells(i, 11)
Town = Range("WordArray").Cells(i, 10)
Town_Check = Range("WordArray").Cells(i, 12)
Current_Date = Range("WordArray").Cells(i, 14)
DTC = Range("WordArray").Cells(i, 15)
Path = Range("Path")
Select Case Rail
Case "Blue Sun"
WordFileName = Range("FileNames").Cells(1, 1)
Case "Clenergy"
WordFileName = Range("FileNames").Cells(2, 1)
Case "Conergy"
WordFileName = Range("FileNames").Cells(3, 1)
Case "Sunlock"
WordFileName = Range("FileNames").Cells(4, 1)
End Select
Set wrdDoc = wrdApp.Documents.Open(Path & WordFileName, , True)
With wrdDoc
With .Bookmarks
.Item("Address").Range = Address
.Item("Current_date").Range = Current_Date
.Item("Job_1").Range = Job
.Item("Job_2").Range = Job
.Item("Lot_Number").Range = Lot_Number
.Item("Panel_Type").Range = Panel_Type
.Item("Panel_Type_2").Range = Panel_Type
.Item("Suburb").Range = Suburb
.Item("Town").Range = Town
.Item("Town_check").Range = Town_Check
If Customer = "Sunlock" Then
.Item("DTC").Range = DTC
End If
End With
wrdDoc.SaveAs (Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".doc")
wrdDoc.ExportAsFixedFormat OutputFileName:=Path & "Lot " & Lot_Number & " " & Address & " " & Suburb & " " & Job & " - s40" & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
.Close ' close the document
End With
Next
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
ScreenUpdating = True
End Sub
Solved it.
Needed to include the Microsoft Word 14.0 Object Library

Resources