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.
Related
This is a scirpt which is supposed to add picture into a Powerpoint Placeholders based on the value of selected cells in an Excel File. Whenever there is an error, the script is supposed to go to the error handling line, fixed it and resume back from where the error was.
However, when the script encounters an error, it will run the error handling line, then end sub. How can I make it resume from where the error was detected?
For example, let's say we have an error on this line
On Error GoTo ERIB
For IB = 6
The script will go to error handling
ERIB:
oSld1.Shapes.AddPicture( _
FileName:="D:\Users\Transparent\AnorMale.png", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=50, Top:=30, Width:=100, Height:=50).Select
After the above code, it will proceed to line ERIE then End Sub.
Instead, I would like the script to continue running from For IB = 7 until the end of the script.
Here's the code
Dim I As Integer
Dim oXL As Object 'Excel.Aplication
Dim OWB As Object 'Excel.workbook
Dim oSld1 As Slide
Dim oSld2 As Slide
Set oXL = CreateObject("Excel.Application")
Set OWB = oXL.Workbooks.Open(FileName:="D:\Users\1. Working\Working.xlsm")
Set oSld1 = ActivePresentation.Slides(1)
Set oSld2 = ActivePresentation.Slides(2)
------------------------------------------------------------------------
On Error GoTo ERIB
For IB = 5 To 7
oSld1.Shapes.AddPicture( _
FileName:="D:\Users\Transparent\" & OWB.Sheets("Listing").Range("B" & CStr(IB)).Value & "_hof.png", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=50, Top:=30, Width:=100, Height:=50).Select
Next IB
On Error GoTo ERIE
For IE = 5 To 7
oSld2.Shapes.AddPicture( _
FileName:="D:\Users\Transparent\" & OWB.Sheets("Listing").Range("E" & CStr(IE)).Value & "_hof.png", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=50, Top:=30, Width:=100, Height:=50).Select
Next IE
OWB.Close
oXL.Quit
Set OWB = Nothing
Set oXL = Nothing
Exit Sub
ERIB:
oSld1.Shapes.AddPicture( _
FileName:="D:\Users\Transparent\AnorMale.png", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=50, Top:=30, Width:=100, Height:=50).Select
ERIE:
oSld1.Shapes.AddPicture( _
FileName:="D:\Users\Transparent\AnorMale.png", _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, Left:=50, Top:=30, Width:=100, Height:=50).Select
End Sub
You can simply put an statement Resume Next at the end of your error handler:
Sub test1()
Dim myValues, sum As Long, count As Long, i As Long
myValues = Array(2, 4, "A", 5, 10)
On Error GoTo ERRHANDLER
For i = LBound(myValues) To UBound(myValues)
sum = sum + myValues(i)
count = count + 1
Next i
Debug.Print "Sum: " & sum & " Count: " & count
Exit Sub
ERRHANDLER:
Debug.Print "error: " & Err.Number, Err.Description
Resume Next
End Sub
Or you can jump to a label:
Sub test2()
Dim myValues, sum As Long, count As Long, i As Long
myValues = Array(2, 4, "A", 5, 10)
On Error GoTo ERRHANDLER
For i = LBound(myValues) To UBound(myValues)
sum = sum + myValues(i)
count = count + 1
CONTINUELOOP:
Next i
Debug.Print "Sum: " & sum & " Count: " & count
Exit Sub
ERRHANDLER:
Debug.Print "error: " & Err.Number, Err.Description
Resume CONTINUELOOP
End Sub
However, consider two things:
a) if you already expect that something specific might fail (in your case adding the picture), it's maybe better to handle that locally. If your main problem is that the AddPicture fails because the image fail is missing, you should check the existance to avoid the error (use for example the Dir-command).
Sub test3()
Dim myValues, sum As Long, count As Long, i As Long
myValues = Array(2, 4, "A", 5, 10)
For i = LBound(myValues) To UBound(myValues)
On Error Resume Next
sum = sum + myValues(i)
If Err.Number <> 0 Then
If Err.Number <> 13 Then Err.Raise Err.Number ' An error occurred and it wasn't Type mismatch
Err.Clear
Else
count = count + 1
End If
On Error Goto 0
Next i
Debug.Print "Sum: " & sum & " Count: " & count
Exit Sub
End Sub
b) You need to be careful what you do in your error handler: If the AddPicture in the error handler fails, it will raise another error and this time it will not be caught. Consider to write a MyAddPicture-routine that does the error handling internally without affecting the rest of your code.
You should consider using a try function so that you encapsulate the error and don't have to go jumping all over the place.
The code below compiles without error but as I don't have your images it hasn't been tested.
Sub Test()
Dim I As Integer
Dim oXL As Object 'Excel.Aplication
Dim OWB As Object 'Excel.workbook
Dim oSld1 As Slide
Dim oSld2 As Slide
Set oXL = CreateObject("Excel.Application")
Set OWB = oXL.Workbooks.Open(Filename:="D:\Users\1. Working\Working.xlsm")
Set oSld1 = ActivePresentation.Slides(1)
Set oSld2 = ActivePresentation.Slides(2)
Dim myParams As Variant
myParams = Array("", msoTrue, msoTrue, 50, 30, 100, 50)
Dim mySLide As PowerPoint.Slide
Const myError As Long = 42 ' put your own error number here
'------------------------------------------------------------------------
For IB = 5 To 7
myParams(0) = "D:\Users\Transparent\" & OWB.Sheets("Listing").Range("B" & CStr(IB)).Value & "_hof.png"
If Not TryAddPictureToSlide(oSld1, myParams, mySLide) Then
myParams(0) = "D:\Users\Transparent\AnorMale.png"
If Not TryAddPictureToSlide(oSld1, myParams, mySLide) Then
Err.Raise _
myError, _
"Could not add " & myParams(0)
End If
End If
'Do whatever needs to be done with myShape
Next IB
For IE = 5 To 7
myParams(0) = "D:\Users\Transparent\" & OWB.Sheets("Listing").Range("E" & CStr(IE)).Value & "_hof.png"
If Not TryAddPictureToSlide(oSld2, myParams, mySLide) Then
myParams(0) = "D:\Users\Transparent\AnorMale.png"
If Not TryAddPictureToSlide(oSld2, myParams, mySLide) Then
Err.Raise _
myError, _
"Could not add " & "D:\Users\Transparent\" & OWB.Sheets("Listing").Range("E" & CStr(IE)).Value & "_hof.png"
End If
End If
Next
'Do whatever needs to be done with myShape
OWB.Close
oXL.Quit
Set OWB = Nothing
Set oXL = Nothing
End Sub
Public Function TryAddPictureToSlide(ByRef ipSlide As PowerPoint.Slide, ByRef ipParams As Variant, opShape As PowerPoint.Shape) As Boolean
On Error Resume Next
Set opShape = _
ipSlide.Shapes.AddPicture _
( _
Filename:=ipParams(0), _
LinkToFile:=ipParams(1), _
SaveWithDocument:=ipParams(2), _
Left:=ipParams(3), _
Top:=ipParams(4), _
Width:=ipParams(5), _
Height:=ipParams(6))
TryAddPictureToSlide = Err.Number = 0
Err.Clear
End Function
I have two Macro scripts, both are working perfectly individually! But I want to marge them and have 1 script.
Basically, I want to save all pages in a WORD document (like 100 pages) as PDF and name each file according to the 3rd line of each page.
So first script is the following which converts to PDF:
Sub SaveAsSeparatePDFs()
Dim strDirectory As String, strTemp As String, ipgEnd As Integer
Dim iPDFnum As Integer, i As Integer
strTemp = InputBox("How many pages is included?" & vbNewLine & "(ex: 60)")
ipgEnd = CInt(strTemp)
strDirectory = Environ("USERPROFILE") & "\Desktop"
iPDFnum = 1
For i = 1 To ipgEnd
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
strDirectory & "\User--" & iPDFnum & FirstPara & ".pdf", ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
wdExportFromTo, From:=i, To:=i + 1, Item:=wdExportDocumentContent, _
IncludeDocProps:=False, KeepIRM:=False, CreateBookmarks:= _
wdExportCreateHeadingBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=False, UseISO19005_1:=False
iPDFnum = iPDFnum + 1
i = i + 1
Next i
End
End Sub
And here is the second script which renames each file according to third line of the WORD doc:
Sub SaveAsWordAndRename()
Dim oSection As Section
Dim r As Range
Dim TempDoc As Document
Dim FirstPara As String
Dim strDirectory As String, strTemp As String, ipgEnd As Integer
Dim iPDFnum As Integer, i As Integer
For Each oSection In ActiveDocument.Sections
Set r = oSection.Range
r.End = r.End - 1
Set TempDoc = Documents.Add
With TempDoc
.Range = r
FirstPara = r.Paragraphs(3).Range.Text
FirstPara = Left(FirstPara, Len(FirstPara) - 1)
.SaveAs FileName:=FirstPara & ".doc"
.Close
End With
Set r = Nothing
Set TempDoc = Nothing
Next
End Sub
How do I rename an OLEObject?
The object is embedded and the oname variable works when used in the other lines but the .name command will not work. There is no error.
Public Sub insertFiles()
Dim newObject As Object
Dim oname As String
Dim CheckName As String
CheckName = UserForm1.MultiPage2.SelectedItem.Caption
oname = CheckName & "_" & "Evidence" & "_" & UserForm1.ProjectName.Value & "_" & Format(Date, "ddmmmyyyy")
Worksheets("Emails").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Set Rng = ActiveCell
Rng.RowHeight = 70
On Error Resume Next
fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
If LCase(fpath) = "false" Then Exit Sub
If UserForm1.ProjectName.Value <> Empty Then
ActiveCell.Value = "."
ActiveSheet.OLEObjects.Add(Filename:=fpath, _
Link:=False, _
DisplayAsIcon:=True, _
IconFileName:="Outlook.msg", _
IconIndex:=1, _
IconLabel:=extractFileName(fpath)).Name = oname
ActiveCell.Offset(0, 1).Value = oname
UserForm1.Attached1.Value = oname
ThisWorkbook.Worksheets("Output").Range("B35").Value = oname
Call UserForm1.Tickbox
UserForm1.LablePIA.Visible = True
UserForm1.Attached1.Visible = True
UserForm1.View.Visible = True
UserForm1.Deleteemail.Visible = True
MsgBox "Attachment uploaded"
Else
MsgBox "Project Name must be input before emails can be uploaded"
End If
End Sub
Public Function extractFileName(filePath)
For i = Len(filePath) To 1 Step -1
If Mid(filePath, i, 1) = "\" Then
extractFileName = Mid(filePath, i + 1, Len(filePath) - i + 1)
Exit Function
End If
Next
End Function
Solution:
The string variable contained too many characters, apparently the max is 35.
OLEObject names cannot exceed 35 characters (presumably unless you use a class module etc!).
Try like this
Dim Obj As OLEObject
set Obj = ActiveSheet.OLEObjects.Add(Filename:=fpath, _
Link:=False, _
DisplayAsIcon:=True, _
IconFileName:="Outlook.msg", _
IconIndex:=1, _
IconLabel:=extractFileName(fpath))
Obj.name = oname
I have about 100 macros in a folder, and I'm looking for one in particular that contains a VBA module with function called addGBE - I forget WHICH file it's in though. Is there any software program that allows me to search within the VBA code of files in a specific folder?
Make Windows Search look within MS Office and other Compressed files
Starting with Microsoft Office 2007, the Office Open XML (OOXML) file formats have become the default file format.
File types such as .XLSX, .XLSM and .DOCX use XML architecture and ZIP compression to store things like text and formulas into cells that are organized into rows and columns. For example, simply changing a .XLSM' file's extension to.ZIP` allows you to open it as a compressed file and view the files that make up the Excel workbook.
By tweaking a few settings we can ensure that Windows Search always searches within OOXML and other compressed file formats.
My example uses Windows 7, but Windows 10 has equivalent settings.
Specify which filetypes should be indexed
Hit +E an browse to the folder where you keep your Office or Compressed files are stored.
Hit Alt+T to open the Tools menu and click Folder Options
Specify which filetypes to always search within
Go to the Search tab
Make sure Always search filenames and contents is selected
Make sure Include compressed is checked
Apply change to other folders:
At this point you can either:
repeat the above steps on any other folders on which you want to change these options, or,
go to the View tab and click Apply to Folders to make all folders look/act like the current one.
Caution! This will copy all of the current folder settings to all other folders, including displayed columns, sort order, view, etc., so be aware that you may lose unique setups for individual folders.
Personally, I'll take the time to setup one folder exactly how I like it, and implement everywhere with a single click.
Open Indexing Options:
Hit the Windows Key
Type index click Indexing Options or hit Enter
click Modify to open a filetree to specify which folders should be included in the Index.
I like to include all folders, but this negatively impacts overall performance if you have a ton of data on the drive(s).
In the Indexing Options dialog:
click the Advanced tab
in the Advanced Options dialog, go to the File Types tab.
This is where you specify which filetypes the indexer should always search within.
Go through the list looking for each Open Office XML filetype (like .XLSM and DOCX)
Select Index Properties and File Contents.
Repeat for any compressed filetypes you want to include (such as .ZIP and .RAR)
When finished click OK
]10
Force re-index:
When you're finished customizing the Indexing options:
On the Indexing Options dialog, click Rebuild to build a new index file.
Note that re-indexing can take a really long time to complete, especially if you're actively using the device and/or you have a ton of data stored locally.
You can optionally close the Indexing dialog with the × and the process will continue in the background.
I found some old code (2006) that I've updated. It will open a box to enter search string then open a dir dialog box to select folder. It will then search through all modules and display a msgbox displaying file name and sheet/module name where string was found. I did not make this, just updated. Orig found here. See here for Microsoft documentation on checking for 64bit and declaring data types properly.
Option Explicit
#If VBA7 And Win64 Then ' VBA7
Declare PtrSafe Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Declare PtrSafe Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Public Type BROWSEINFO
hOwner As LongPtr
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As LongPtr
lParam As LongPtr
iImage As Long
End Type
#Else ' Downlevel when using previous version of VBA7
Declare PtrSafe Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Declare PtrSafe Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
#End If
Function GetDirectory(Optional Msg) As String
Dim bInfo As BROWSEINFO
Dim Path As String
Dim R As Long
Dim x As Long
Dim pos As Integer
'Root folder (&H0 for Desktop, &H11 for My Computer)
bInfo.pidlRoot = &H0
'Title in the dialog
If IsMissing(Msg) Then
bInfo.lpszTitle = "Select a folder."
Else
bInfo.lpszTitle = Msg
End If
'Type of directory to return
bInfo.ulFlags = &H1
'Display the dialog
x = SHBrowseForFolder(bInfo)
'Parse the result
Path = Space$(512)
R = SHGetPathFromIDList(ByVal x, ByVal Path)
If R Then
pos = InStr(Path, Chr$(0))
GetDirectory = Left(Path, pos - 1)
Else
GetDirectory = ""
End If
End Function
Function RecursiveFindFiles(strPath As String, _
strSearch As String, _
Optional bSubFolders As Boolean = True, _
Optional bSheet As Boolean = False, _
Optional lFileCount As Long = 0, _
Optional lDirCount As Long = 0) As Variant
'adapted from the MS example:
'http://support.microsoft.com/default.aspx?scid=kb;en-us;185476
'---------------------------------------------------------------
'will list all the files in the supplied folder and it's
'subfolders that fit the strSearch criteria
'lFileCount and lDirCount will always have to start as 0
'---------------------------------------------------------------
Dim strFileName As String 'Walking strFileName variable.
Dim strDirName As String 'SubDirectory Name.
Dim arrDirNames() As String 'Buffer for directory name entries.
Dim nDir As Long 'Number of directories in this strPath.
Dim i As Long 'For-loop counter.
Dim n As Long
Dim arrFiles
Static strStartDirName As String
Static strpathOld As String
On Error GoTo sysFileERR
If lFileCount = 0 Then
Static collFiles As Collection
Set collFiles = New Collection
Application.Cursor = xlWait
End If
If Right$(strPath, 1) <> "\" Then
strPath = strPath & "\"
End If
If lFileCount = 0 And lDirCount = 0 Then
strStartDirName = strPath
End If
'search for subdirectories
'-------------------------
nDir = 0
ReDim arrDirNames(nDir)
strDirName = Dir(strPath, _
vbDirectory Or _
vbHidden Or _
vbArchive Or _
vbReadOnly Or _
vbSystem) 'Even if hidden, and so on.
Do While Len(strDirName) > 0
'ignore the current and encompassing directories
'-----------------------------------------------
If (strDirName <> ".") And (strDirName <> "..") Then
'check for directory with bitwise comparison
'-------------------------------------------
If GetAttr(strPath & strDirName) And vbDirectory Then
arrDirNames(nDir) = strDirName
lDirCount = lDirCount + 1
nDir = nDir + 1
DoEvents
ReDim Preserve arrDirNames(nDir)
End If 'directories.
sysFileERRCont1:
End If
strDirName = Dir() 'Get next subdirectory
DoEvents
Loop
'Search through this directory
'-----------------------------
strFileName = Dir(strPath & strSearch, _
vbNormal Or _
vbHidden Or _
vbSystem Or _
vbReadOnly Or _
vbArchive)
While Len(strFileName) <> 0
'dump file in sheet
'------------------
If bSheet Then
If lFileCount < 65536 Then
Cells(lFileCount + 1, 1) = strPath & strFileName
End If
End If
lFileCount = lFileCount + 1
collFiles.Add strPath & strFileName
If strPath <> strpathOld Then
Application.StatusBar = " " & lFileCount & _
" " & strSearch & " files found. " & _
"Now searching " & strPath
End If
strpathOld = strPath
strFileName = Dir() 'Get next file
DoEvents
Wend
If bSubFolders Then
'If there are sub-directories..
'------------------------------
If nDir > 0 Then
'Recursively walk into them
'--------------------------
For i = 0 To nDir - 1
RecursiveFindFiles strPath & arrDirNames(i) & "\", _
strSearch, _
bSubFolders, _
bSheet, _
lFileCount, _
lDirCount
DoEvents
Next
End If 'If nDir > 0
'only bare main folder left, so get out
'--------------------------------------
If strPath & arrDirNames(i) = strStartDirName Then
ReDim arrFiles(1 To lFileCount) As String
For n = 1 To lFileCount
arrFiles(n) = collFiles(n)
Next
RecursiveFindFiles = arrFiles
Application.Cursor = xlDefault
Application.StatusBar = False
End If
Else 'If bSubFolders
ReDim arrFiles(1 To lFileCount) As String
For n = 1 To lFileCount
arrFiles(n) = collFiles(n)
Next
RecursiveFindFiles = arrFiles
Application.Cursor = xlDefault
Application.StatusBar = False
End If 'If bSubFolders
Exit Function
sysFileERR:
Resume sysFileERRCont1
End Function
Function FileFromPath(ByVal strFullPath As String, _
Optional bExtensionOff As Boolean = False) _
As String
Dim FPL As Long 'len of full path
Dim PLS As Long 'position of last slash
Dim pd As Long 'position of dot before exension
Dim strFile As String
On Error GoTo ERROROUT
FPL = Len(strFullPath)
PLS = InStrRev(strFullPath, "\", , vbBinaryCompare)
strFile = Right$(strFullPath, FPL - PLS)
If bExtensionOff = False Then
FileFromPath = strFile
Else
pd = InStr(1, strFile, ".", vbBinaryCompare)
FileFromPath = Left$(strFile, pd - 1)
End If
Exit Function
ERROROUT:
On Error GoTo 0
FileFromPath = ""
End Function
Sub SearchWBsForCode()
Dim strTextToFind As String
Dim strFolder As String
Dim arr
Dim i As Long
Dim strWB As String
Dim VBProj As VBProject
Dim VBComp As VBComponent
Dim lStartLine As Long
Dim lEndLine As Long
Dim lFound As Long
Dim lType As Long
Dim lSkipped As Long
Dim oWB As Workbook
Dim bOpen As Boolean
Dim bNewBook As Boolean
strTextToFind = InputBox("Type the text to find", _
"finding text in VBE")
If Len(strTextToFind) = 0 Or StrPtr(strTextToFind) = 0 Then
Exit Sub
End If
strFolder = GetDirectory()
If Len(strFolder) = 0 Then
Exit Sub
End If
lType = Application.InputBox("Type file type to search" & _
vbCrLf & vbCrLf & _
"1. Only .xls files" & vbCrLf & _
"2. Only .xla files" & vbCrLf & _
"3. Either file type", _
"finding text in VBE", 1, Type:=1)
Select Case lType
Case 1
arr = RecursiveFindFiles(strFolder, "*.xls", True, True)
Case 2
arr = RecursiveFindFiles(strFolder, "*.xla", True, True)
Case 3
arr = RecursiveFindFiles(strFolder, "*.xl*", True, True)
Case Else
Exit Sub
End Select
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
For i = 1 To UBound(arr)
Application.StatusBar = i & "/" & UBound(arr) & _
" - Searching " & arr(i)
strWB = FileFromPath(arr(i))
On Error Resume Next
Set oWB = Workbooks(strWB)
If oWB Is Nothing Then
bOpen = False
Workbooks.Open arr(i)
Else
'for preventing closing WB's that are open already
bOpen = True
Set oWB = Nothing
End If
bNewBook = True
For Each VBComp In Workbooks(strWB).VBProject.VBComponents
If Err.Number = 50289 Then 'for protected WB's
lSkipped = lSkipped + 1
Err.Clear
GoTo PAST
End If
lEndLine = VBComp.CodeModule.CountOfLines
If VBComp.CodeModule.Find(strTextToFind, _
lStartLine, _
1, _
lEndLine, _
-1, _
False, _
False) = True Then
If bNewBook = True Then
lFound = lFound + 1
bNewBook = False
End If
Application.ScreenUpdating = True
If MsgBox("Workbook: " & arr(i) & vbCrLf & _
"VBComponent: " & VBComp.Name & vbCrLf & _
"Line number: " & lStartLine & _
vbCrLf & vbCrLf & _
"WB's found so far: " & lFound & vbCrLf & _
"Protected WB's skipped: " & lSkipped & _
vbCrLf & vbCrLf & _
"Stop searching?", _
vbYesNo + vbDefaultButton1 + vbQuestion, _
i & "/" & UBound(arr) & _
" - found " & strTextToFind) = vbYes Then
With Application
.StatusBar = False
.EnableEvents = True
.DisplayAlerts = True
End With
With VBComp.CodeModule.CodePane
.SetSelection lStartLine, 1, lStartLine, 1
.Show
End With
Exit Sub
End If
Application.ScreenUpdating = False
End If
Next
PAST:
If bOpen = False Then
Workbooks(strWB).Close savechanges:=False
End If
On Error GoTo 0
Next
On Error Resume Next
If bOpen = False Then
Workbooks(strWB).Close savechanges:=False
End If
With Application
.ScreenUpdating = True
.StatusBar = False
.EnableEvents = True
.DisplayAlerts = True
End With
MsgBox lFound & " WB's found with " & strTextToFind & " in VBE" & _
vbCrLf & vbCrLf & _
"protected WB's skipped: " & lSkipped, , _
"finding text in VBE"
End Sub
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