Question : Error Type mistach when creating and running Excel macro through Access

Hi Experts,

I'm using the below codes in Access to create a simple macro on Excel and run it.
But I got the error "Type Mismatch" when it comes to the line
  xls.Application.Run "ThisWorkbook.CleanXL"

Can anyone help me with this?

Thanks.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
Public Sub ExcelMacro()
  Dim xls, strCode
  Dim xlPath As String
  xlPath = "F:\myProject\myExcelFile.xls"
  Set xls = CreateObject("Excel.Application")
  xls.Visible = True
  xls.Workbooks.Open (xlPath)
  
  'Create Macro on fly:
  strCode = "Public Sub CleanXL()" & vbCrLf
  strCode = strCode & "Worksheets(" & Chr(34) & "Sheet1" & Chr(34) & ").Columns(" & Chr(34) & "A:A,C:I,K:P" & Chr(34) & ").Delete" & vbCrLf
  strCode = strCode & "End Sub"
  'Add Macro to Excel:
  xls.ActiveWorkbook.VBProject.VBComponents.Item(1).CodeModule.AddFromString strCode
 
  'Run Macro, error occurs...
  xls.Application.Run "ThisWorkbook.CleanXL"
 
  'Close Excel without saving:
  xls.ActiveWorkbook.Close False
  xls.Quit
  
  Set xls = Nothing
  Set strCode = Nothing
End Sub

Answer : Error Type mistach when creating and running Excel macro through Access

Or, try this variation, which saves a copy of the modified workbook, and imports that, not the original.

Also, I don't know if you knew, but the code you posted was importing a different file to the one you were modifying.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
Public Sub ImportXL()
 
     Const xlPath As String = "F:\MIS consolidation tool\Source files\Securities_1.xls"
     Const xlPathTemp As String = "F:\MIS consolidation tool\Source files\TEMP_Securities_1.xls"
 
     Dim acExcel, wb 
     Set acExcel = CreateObject("Excel.Application")
     acExcel.Visible = False
 
     Set wb = acExcel.Workbooks.Open(xlPath)
     wb.Worksheets("Sheet1").Range("A:A,C:E,G:I,K:P").Delete
     wb.SaveCopyAs xlPathTemp
     wb.Close False
     Set wb = Nothing
     acExcel.Quit
     Set acExcel = Nothing
 
     DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel3, _
                               "TempDoneTrades", xlPathTemp, True
                               
     Kill xlPathTemp
 
End Sub
Random Solutions  
 
programming4us programming4us