We help IT Professionals succeed at work.
Get Started

VBA to update field values on a table during a loop

KP_SoCal asked
Last Modified: 2013-11-28
The block of code below imports specific worksheets from 3 different Excel files into one table.  Immediately after ‘Year1.xlsx’ is imported into ‘tblMaster’, I need to update the value for each record under field name ‘fldYear’ in the target table (‘tblMaster’).  

The value it would update to is from the form control of “[forms]![frmName]![txtYear1]”.

Then when ‘Year2.xlsx’ is imported, ‘fldYear’ would be updated with value listed in “[forms]![frmName]![txtYear2]”.  Then the same suit would be followed when importing ‘Year3.xlsx”.

Any insight into this?
Public Sub ImportExcelSheetsfIANL()
Dim objXL As Object
Dim sTable, xlPath As String, i As Integer

Dim myPath(), j, iCnt As Integer
myPath = Array("\\server\Year1.xlsx", _
               "\\server\Year2.xlsx", _
For j = LBound(myPath) To UBound(myPath)
If Dir(myPath(j)) <> "" Then

Set objXL = CreateObject("Excel.Application")
    objXL.Workbooks.Open myPath(j), , True
    With objXL
        For i = 1 To .Worksheets.Count
            If InStr(.Worksheets(i).Name, "widget") Then
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, _
             "tblMaster", myPath(j), True, .Worksheets(i).Name & "!A:M"
            End If
    End With
    Set objXL = Nothing

    iCnt = iCnt + 1
End If
If iCnt = 3 Then
MsgBox "Worksheets do not exist. Exiting sub now!", vbInformation, "Error"
Exit Sub
End If

Open in new window

Watch Question
Top Expert 2016
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE