Public Function AddToDictionary(FilePath As String, SheetName As String)
On Error Resume Next
' Create Excel Object
Dim XL As Excel.Application
Set XL = GetObject(, "Excel.Application")
If XL Is Nothing Then
Set XL = CreateObject("Excel.Application")
End If
Dim wb As Workbook
Dim i As Long
Set wb = XL.Workbooks.Open(FilePath)
Set mysheet = wb.Sheets(SheetName)
' Create Dictionary
Set translator_dict = CreateObject("Scripting.Dictionary")
' Number of rows in first column of sheet
NumRows = mysheet.Range("A2", mysheet.Range("A2").End(xlDown)).Rows.Count
' Append sheet data to dictionary
For i = 1 To NumRows + 1
If Not IsEmpty(mysheet.Cells(i, 1).Value) Then
translator_dict.add key:=LCase(mysheet.Cells(i, 1).Value()), Item:=mysheet.Cells(i, 2).Value()
End If
Next i
Set mysheet = Nothing
wb.Close 'Added
Set wb = Nothing
xl.Quit 'Added
Set XL = Nothing
Set AddToDictionary = translator_dict
End Function
See my changes above. If you add the line to quit xl, you can add logic to check the Workbooks collection first. If there are still workbooks open, the Count will be greater than 0. So if the Count is 0, you can Quit xl.
Also, I highly recommend that you leave the xl object creation in its own sub. A lot of people assume that On Error Resume Next only applies to the next line. But it stays in effect during the scope of the sub. IOW, it will suppress all errors in your sub unless you reset it. Search VBA help for "On Error Statement" topic on how to do that. The preferred method is to containerize your code. Keep tasks separate. Besides, there may come a time when you want to use that function for another sub.
Also, you didn't Dim the NumRows variable. VBA will handle it for you at runtime, but it will always be cast as a Variant. If you include Option Explicit statement at the top of your module, the IDE will remind you that you didn't dim a var. If you go Tools>Options>Editor tab and check "Require Variable Declaration", it will add the Option Explicit statement for you when you create a new module.
Ed
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to
post your code.