Type Mismatch with Workbooks.Open - excel

I have a larger code set to help automate an auditing model. I am attempting to add a function to import a claims file. I have a "GetFiles" function I use regularly to import information but now I am receiving type mismatch error.
I have already tried different variable assignments and fully quantifying different items but it appears to err out regardless. Originally I was doing OpenFile = GetFiles (see commented line) and then my formula read as set aux = application.workbooks.open(OpenFile) but same error
This is a small section of the code so a number of the variables declared are not visible in this snippet.There is also some commented out lines regarding "ThisWorkbook" as the module will be moved from my personal working file into an actual template model.
Sub Audit_Template_Autofill()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim column_id() As Variant, A1 As Range, Z As Range, c As Range
Dim column_count As Long, x As Long, input_option() As Variant, Loop_Input As Variant
Dim claims As Worksheet, audit As Worksheet, OpenFile As Variant, aux As Workbook
'run function to get claims file for import
'GetFiles
' Set claims = ThisWorkbook.Sheets("Claims Data")
' Set audit = ThisWorkbook.Sheets("Audit")
Set claims = ActiveWorkbook.Sheets("Claims Data")
Set audit = ActiveWorkbook.Sheets("Audit")
'OpenFile = GetFiles
Set aux = Application.Workbooks.Open(GetFiles)
ActiveWorkbook.ActiveSheet.Cells.Select.Copy
claims.Range("A1").Paste
Set A1 = claims.Range("A1")
Set Z = A1.End(xlToRight).Offset(0, 1)
column_count = claims.Range(A1, Z).Count
ReDim column_id(0 To column_count): ReDim input_option(0 To column_count)
For Each c In Range(A1, Z)
column_id(x) = c.Value
x = x + 1
Next c
x = 0
Do While x <= column_count
input_option(x) = x + 1 & "=" & column_id(x)
x = x + 1
Loop
x = 0
Do While x <= column_count
Loop_Input = Loop_Input & input_option(x) & vbCrLf & ""
x = x + 1
Loop
the error occurs on the set aux = Application.Workbooks.open(GetFiles)
Here is the Function GetFiles
Function GetFiles() As Variant
GetFiles = Application.GetOpenFilename(Title:="Select Files(s)", MultiSelect:=True)
End Function
I expect the function to allow me to open a workbook, then it will proceed to import the information and move forward with the code. The file selection box appears, but when I pick an excel file and hit OK, I receive the type mismatch error. Apologies for long winded text, still new to Stack Overflow. Thanks again!

Related

Extract paragraphs from word to excel

I am trying to extract specific paragraphs from word to excel. I have an error with my code about the ".Text" part : "Method or data not found". Any idea why? Thanks!
Sub extract()
Dim p As Object
Dim xl
Dim wb, ws, xlr
Dim a As Variant
Dim b As Variant
Set xl = CreateObject("Excel.Application")
xl.Visible = True
Set wb = xl.Workbooks.Add
Set ws = wb.Worksheets(1)
i = 1
j = 1
c = 1
For Each p In ActiveDocument.Paragraphs
If Len(p) > 200 Then
Set xlr = ws.Range("b" & i)
ActiveDocument.Paragraphs(j).Range.Copy
xlr.Value = ActiveDocument.Range.Paragraphs(j).Text
Set xlr = ws.Range("a" & i)
c = j - 1
If c > 1 Then
ActiveDocument.Paragraphs(c).Range.Copy
xlr.Value = ActiveDocument.Range.Paragraphs(c).Text
End If
ws.Range("c" & i) = Date
i = i + 1
End If
j = j + 1
Next
End Sub
Ensure that under Tools | Options | Editor you have
"Require Variable Declaration" checked as shown below. This will
automatically place Option Explicit at the top of each new module
you create and will prevent you from creating variables without
declaring them first.
All variables must be declared in the form Dim name As DataType,
otherwise they default to a datatype of Variant
Variables that are declared on the same line must each be given a datatype, i.e. Dim wb As Object, ws As Object, xlr As Object. Any that don't have a datatype will default to a datatype of Variant
.Text is throwing an error as you have Range in the wrong place. It should be ActiveDocument.Paragraphs(j).Range.Text. This is something that Intellisense would have shown you as you typed.
When coding across Office applications use Tools | References to add the relevant library and avoid using Object (aka Late Binding). This will help ensure that the datatypes are correct and make your coding easier. There is no advantage to late binding when you are just using the Office libraries.

Getting an Invalid Qualifier error. I am trying to print the common brands from a workbook to another with help of an array

The code when run shows no error but no values are being printed:
Sub HouseOfCommons()
Dim filePath As String
filePath = "D:\"
Dim Brands(100) As String
Dim QuesRange(4) As String
QuesRange(0) = "A10:F125"
QuesRange(1) = "A137:F254"
QuesRange(2) = "A266:F307"
QuesRange(3) = "A319:F362"
QuesRange(4) = "A373: F415"
Dim inputx As String
inputx = InputBox("Enter the brand")
For I = 0 To 4
Workbooks.Open (filePath + "JP_CP_2019Q3_Data Tables.xlsx")
ActiveWorkbook.Worksheets("P_2_3w").Select
If (Workbooks("JP_CP_2019Q3_Data Tables.xlsx").Worksheets("P_2_3w").Range("A137:A500").Find(inputx)) = True Then
If (Brands.Contains(inputx)) = False Then
Brands.Add (inputx)
For x = 1 To UBound(Brands)
Workbooks.Open ("D:\InProcess.xlsm")
ThisWorkbook.Sheets("Sheet2").Cells.Value(I, 1) = inputx
Next x
End If
End If
Next I
End Sub
The code should store the common brands into an array and print them in a separate workbook called "InProcess.xlsm"
You're using .NET syntax which is not supported in VBA:
If (Brands.Contains(inputx)) = False Then
possible replacement:
If IsError(Application.Match(inputx, Brands, 0)) Then
Your code seems to have other problems but without knowing what it's supposed to do it's difficult to offer suggested fixes.

Access to Excel: Decrease Runtime of Excel VBA

Similar versions of this question probably have been asked before, but I had questions regarding this issue.
Basically for my function, I just want to run simple a spell check on selected tables from Microsoft Access. Since Access doesn't support individual highlighting all too well in reports, I have the data exported to an Excel file and have VBA run tests for any errors there. After searching online for tips, I have the current code to run faster than what I originally had. But ideally no matter the size of the table I want the function to run under 10 minutes. But currently for some of them, for tables that have 500k+ cells the runtime can still go past 30 minutes. So I was wondering if anything further can be done to better enhance the runtime of this.
Private Function Excel_Parser(outFile As String, errorCount As Integer, ByVal tName As String)
' EXCEL SETUP VARIABLES
Dim OpenApp As Excel.Application
Set OpenApp = CreateObject("Excel.Application")
Dim parserBook As Excel.Workbook
Dim parserSheet As Excel.Worksheet
' Opening exported file
Set parserBook = OpenApp.Workbooks.Open(outFile, , , , , , , , , , , , , , XlCorruptLoad.xlRepairFile)
If parserBook Is Nothing Then
status2 = "Failed to set Workbook"
Exit Function
Else
status3 = "Searching [" & tName & "] for errors"
Set parserSheet = parserBook.Worksheets(1)
' --------------------------------------------------------------------------------
' Fetch Table information
lastCellAddress = parserSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address
Dim rng As Range
Set rng = parserSheet.Range("A1:" & lastCellAddress)
' --------------------------------------------------------------------------------
' Populating entire table data from Excel into array to save runtime.
Dim dataArr() As Variant, R As Long, C As Long
dataArr = rng.Value2
' Parsing through table data array
nRows = UBound(dataArr, 1)
nCols = UBound(dataArr, 2)
fileOuterLoop1 = Time
For R = 1 To nRows
For C = 1 To nCols
cCell = CStr(dataArr(R, C))
status4 = "Now running check on cell: [" & cCell & "]"
If cCell <> "" Or Not (IsNull(cCell)) Then
If Not OpenApp.Application.CheckSpelling(cCell) Then
errorCount = errorCount + 1
' Change cell status
vArr = Split(parserSheet.Cells(1, C).Address(True, False), "$")
fCol = vArr(0)
xDef = fCol & R
parserSheet.Range(xDef).Interior.Color = RGB(255, 213, 124)
End If
End If 'End of cCell is null check
Next C
Next R
fileOuterLoop2 = Time
fCheck = Format(fileOuterLoop2 - fileOuterLoop1, "hh:mm:ss")
' --------------------------------------------------------------------------------
parserSheet.Columns.AutoFit
status7 = "Loop Finished. Runtime: " & fCheck
' Save and Cleanup
OpenApp.DisplayAlerts = False
parserBook.SaveAs FileName:=outFile, FileFormat:=xlWorkbookDefault, ConflictResolution:=xlLocalSessionChanges
parserBook.Saved = True
parserBook.Close SaveChanges:=False
OpenApp.DisplayAlerts = True
Set parserSheet = Nothing
Set parserBook = Nothing
Set OpenApp = Nothing
' Return errorCount for database
Excel_Parser = errorCount
End If
End Function
outFile is a PATH string, where file exists from a TransferSpreadsheet command. And "status" variables are just error log textboxes in the Access form. I have tried adding in both Access' and Excel's versions of ScreenUpdating or Echo but I found that these commands actually make my function runtime slightly slower.
Two things:
Do you use status4 somewhere in your code to show current state of work and just omitted it here in the sample? If so, think about not displaying it for every loop, but maybe only every 50 steps by using Mod operator.
See https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/mod-operator
You should avoid screen refreshs and more on every loop in Excel by setting this before the loop:
OpenApp.ScreenUpdating = False
OpenApp.EnableEvents = False
OpenApp.Calculation = Excel_XlCalculation.xlCalculationManual
And this after the loop:
OpenApp.ScreenUpdating = True
OpenApp.EnableEvents = True
OpenApp.Calculation = Excel_XlCalculation.xlCalculationAutomatic
It can end in a massive speed up. Give it a try.

Object Variable or With block variable not set mid-loop

The issue I've got here is that
iRow = PullRange.Find(What:=a(x, 0)).Row - 1
Throws above mentioned error in the middle of a loop. The thing is it works for the first handful of iterations of x, but at x = 11/iRow = 30 it breaks and I've no clue why. There's nothing unique about that particular row and yet it crashes, has anyone any clue as to why?
Let me know if more info is needed.
Public Sub DataDump(Sql As String, PullColumn As String)
Dim a() As Variant
Dim iRow As Integer
Dim PullRange As Range
Dim DumpRange As Range
Dim x As Integer
Dim y As Integer
Set PullRange = Range(PullColumn & ":" & PullColumn)
Set DumpRange = Range("H1")
Set recs = New ADODB.Recordset
recs.Open Sql, con, adOpenDynamic
a = recs.GetRows
'a(y, x)
For x = 0 To UBound(a, 2)
If IsNull(a(0, x)) Then GoTo none
iRow = PullRange.Find(What:=a(0, x)).Row - 1
If iRow = 0 Then GoTo none
For y = 1 To UBound(a, 1)
Debug.Print a(y, x)
If IsNull(a(y, x)) Then GoTo Err
DumpRange.Offset(iRow, y) = a(y, x)
Err:
Next y
none:
Next x
End Sub
#Rory Was right. Unclean data caused the loop to break and I couldn't see the difference because the difference was minute, after inserting data set anew from the same source it fixed itself. Lesson learned.

looping a DateLastModified function through a column in excel

I have a worksheet with data but I need to add the time at which the Data was created. This time is the "Last Modified"-time of the file I got the data from.
I already got all the filenames as in "filename.txt" in the first column of the worksheet so each line of data can be referenced to its file. I have this function to pull the LastModified-Date from the filename:
Function FileLastModified(strFullFileName As String)
strFullFileName = "C:\...\filefolder\" + Range("A1").Value
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
s = f.DateLastModified
FileLastModified = s
Set fs = Nothing: Set f = Nothing
End Function
Now I want the function to go through all the filenames in column A and put all the LastModified-Times in column D. So how do I edit this
strFullFileName = "C:\.....\" + Range("A1").Value
to automatically pull the filename from the A-Column?
Something like this?
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim i As Long
Dim n As Long
Dim filenames As Variant
Dim lastModifiedTimes As Variant
'How many filenames are there? (should tailor this to your exact situation)
n = Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious).Row
filenames = Range("A1").Resize(n, 1).Value 'load all fnames from sheet to array
ReDim lastModifiedTimes(1 To n, 1 To 1)
For i = 1 To n
lastModifiedTimes(i,1) = _
FSO.GetFile("C:\.....\" & filenames(i,1)).DateLastModified
Next i
'Slap times array onto sheet
Range("D1").Resize(n, 1).Value = lastModifiedTimes
Note that I got rid of your FileLastModified wrapper function since it's really only wrapping one thing, and it can be replaced by one single line of code.

Resources