VBA Automatically add autocorrection entries in word from an excel list - vba

I am trying to add a huge amount of autocorrect entries into WORD loading the data of an excel file/sheet.
This is actually not with Autocorrections purposes but in order to use shortcuts to introduce complete paragraphs to write much faster.
First I tried:
Sub autocorrectlist()
'TRYING OUT IF using variables works for a new autocorrect entry.
Dim myString1 As String
Dim myString2 As String
myString1 = "BBBB"
myString2 = "BBBB works works works"
AutoCorrect.Entries.Add Name:=myString1, Value:=myString2
This worked. when writing BBBB in Word get substitute by the other expression.
lets try to read values from the excel file.
It is a big long here the code but it consist basically in open an excel file and read the entries of an excel sheet, one column being the entries for the so called shortcut (the text that has to be substitute) and the other one the substituting text)
'lets create a huge list of modifiers
Dim i As Integer 'counter
'Read Excel File Megaclause
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
'specify the workbook to work on
WorkbookToWorkOn = "C:\Users\JF30443\Desktop\WORK\EXCEL\megaclause7.xlsm"
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
On Error GoTo Err_Handler
oXL.Visible = True
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
'Process each of the spreadsheets in the workbook
Dim mySht As Worksheet
Set mySht = oWB.Worksheets("sc6")
Dim lastRow As Integer
lastRow = mySht.Cells(mySht.Rows.Count, "A").End(xlUp).Row
Dim myName As String
Dim myAuto As String
'reading the values from the sheet
For i = 1 To lastRow
myName = mySht.Cells(i, 1).Value
myAuto = mySht.Cells(i, 2).Value
If myName <> "" And myAuto <> "" Then
MsgBox ("nr:" & i & "myName:" & myName & "//myauto:" & myAuto)
'note here: actually it read correctly the two first values of the SC6 sheet
'Since the values displayed by the msgbox are correct
'the following line gives an error
Application.AutoCorrect.Entries.Add Name:=myName, Value:=myAuto
'the error being:
'AutoCorrect cannot replace text which contains a space character.
End If
Next
If ExcelWasNotRunning Then
oXL.Quit
End If
'Make sure you release object references.
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If ExcelWasNotRunning Then
oXL.Quit
End If
End Sub
As stated in the code between lines the code reads the sheet because the msgbox displays correctly the two first values of the sheet called "SC3" but inmediatly after it gives error.
I copied partially this code from internet, but the one I thought would be the most difficult part (reading from word in excel) works, and then I can not add the entry.
What is even more strange is that the first part of the code above pasted (the one with "BBBB") works, which is basically the same approach as in the loop.
I searched for info in the net but I did not find anything relevant relating to taht error.
Help is welcome
Thanks.

The problem was an initial space in the names of the sheet

Related

Macro VBA: Match text cells across two workbooks and paste

I need help modifying a macro that matches the part number (Column C) between two sheets in different workbooks. Then it pastes the info from 'Original' sheet from the range P9:X6500 into the 'New' sheet into the range P9:X6500. The first sheet 'Original' in column C range C9:C6500 is the matching part number column. The 'New' sheet has the same column C with the part number to match. I only want match and paste the visible values.
I originally had this macro code which copy pastes only visible values from one workbook to another that I would like to modify it to match and copy paste:
Sub GetDataDemo()
Const FileName As String = "Original.xlsx"
Const SheetName As String = "Original"
FilePath = "C:\Users\me\Desktop\"
Dim wb As Workbook
Dim this As Worksheet
Dim i As Long, ii As Long
Application.ScreenUpdating = False
If IsEmpty(Dir(FilePath & FileName)) Then
MsgBox "The file " & FileName & " was not found", , "File Doesn't Exist"
Else
Set this = ActiveSheet
Set wb = Workbooks.Open(FilePath & FileName)
With wb.Worksheets(SheetName).Range("P9:X500")
On Error Resume Next
.SpecialCells(xlCellTypeVisible).Copy this.Range("P9")
On Error GoTo 0
End With
End If
ThisWorkbook.Worksheets("NEW").Activate
End Sub
Also here is what I want it to look like:
Original
NEW
I appreciate the help!
try the following where it copies the range from one sheet to the other. You can break up With wb.Worksheets(SheetName).Range("P9:X500") into With wb.Worksheets(SheetName) then use .Range("P9:X500").Copy this.Range("P9") inside the With statement. Avoid using names like i or ii or this and use something more descriptive. The error handling is essentially only dealing with Sheets not being present and i think better handling of that scenario could be done. Finally, you need to turn ScreenUpdating back on to view changes.
Option Explicit
Public Sub GetDataDemo()
Const FILENAME As String = "Original.xlsx"
Const SHEETNAME As String = "Original"
Const FILEPATH As String = "C:\Users\me\Desktop\"
Dim wb As Workbook
Dim this As Worksheet 'Please reconsider this name
Application.ScreenUpdating = False
If IsEmpty(Dir(FILEPATH & FILENAME)) Then
MsgBox "The file " & FILENAME & " was not found", , "File Doesn't Exist"
Else
Set this = ActiveSheet
Set wb = Workbooks.Open(FILEPATH & FILENAME)
With wb.Worksheets(SHEETNAME)
'On Error Resume Next ''Not required here unless either of sheets do not exist
.Range("P9:X500").Copy this.Range("P9")
' On Error GoTo 0
End With
End If
ThisWorkbook.Worksheets("NEW").Activate
Application.ScreenUpdating = True ' so you can see the changes
End Sub
UPDATE: As OP wants to match between sheets on column C in both and paste associated row information across (Col P to Col X) second code version posted below
Version 2:
Option Explicit
Public Sub GetDataDemo()
Dim wb As Workbook
Dim lookupRange As Range
Dim matchRange As Range
Set wb = ThisWorkbook
Set lookupRange = wb.Worksheets("Original").Range("C9:C500")
Set matchRange = wb.Worksheets("ThisSheet").Range("C9:C500")
Dim lookupCell As Range
Dim matchCell As Range
With wb.Worksheets("Original")
For Each lookupCell In lookupRange
For Each matchCell In matchRange
If Not IsEmpty(matchCell) And matchCell = lookupCell Then 'assumes no gaps in lookup range
matchCell.Offset(0, 13).Resize(1, 9).Value2 = lookupCell.Offset(0, 13).Resize(1, 9).Value2
End If
Next matchCell
Next lookupCell
End With
ThisWorkbook.Worksheets("NEW").Activate
Application.ScreenUpdating = True
End Sub
You may need to amend a few lines to suit your environment e.g. change this to meet your sheet name (pasting to).
Set matchRange = wb.Worksheets("ThisSheet").Range("C9:C500")

Using Word VBA to automate Excel, I get Run-time error '13': Type mismatch when using the .Find function

I'm trying to get data from an excel sheet to a word document. I try using the 'Find' function however I keep getting the same error "Type mismatch" on this line:
Set FoundRange = .Cells.Find(260707)
Here is the subroutine I am running.
Sub GetID()
Dim oXL As Object
Dim oWB As Object
Dim oSheet As Object
Dim WorkbookToWorkOn As String
Dim FoundRange As Range
Dim dummyvar As String
'Start a new instance of Excel
Set oXL = CreateObject("Excel.Application")
'Line to make Excel Visible or not
oXL.Visible = False
'Open the workbook
'Set the file path to access the 'Certified Personnel' table
WorkbookToWorkOn = "\\DataSource\CertifiedPersonnel.xlsx"
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
Set oSheet = oXL.ActiveWorkbook.Sheets("tblCertifiedPersonnel")
'End of Excel Automation. Everything from this point on can reference Excel.
With oSheet
dummyvar = .Cells(1, 2).Text
.Cells(1, 2).Select
'Set the range of the cell containing the ID number
'If the ID was found
Set FoundRange = .Cells.Find(260707)
If Not FoundRange Is Nothing Then
'Set the NTlogin equal to the value of column 1, and row corresponding to the FoundRange row
NTlogin = .Cells(FoundRange.Rows, 1).Text
Role = .Cells(FoundRange.Rows, 4).Text
End If
End With
'End Excel reference
oXL.ActiveWorkbook.Close SaveChanges:=False
oXL.Application.Quit
Set oXL = Nothing
Set oWB = Nothing
Set oSheet = Nothing
End Sub
I know it is accessing the correct workbook, because the dummy variable (dummyvar) is returning the value I expect. I have tried several things related to the 'Find' function, however I have not been able to get it to work. Any ideas? Much appreciated.
You are using late binding and have FoundRange declared as a Range. Since this is in a Word document, you're implicitly declaring it as a Word.Range here:
Dim FoundRange As Range
.Find is returning an Excel.Range. Change it to:
Dim FoundRange As Object
With the assumption that the ID values are stored as text in the worksheet, either with a cell type of Text or with an apostrophe/single-quote in front of the number, you may need to format the ID as string. With the further assumption that eventually you may want to pass the ID via parameter to the procedure, give this a try:
Set FoundRange = .Cells.Find(CStr(260707))
That will also allow you to replace the constant number with a variable if desired.

Frustration with VBA copy-paste from workbook to workbook

I've been trying to figure out this subroutine for days. I have read every post about VBA copy-paste on this site and haven't found the answer yet. The concept is so simple but when I run it from a command button, it stops after the copy workbook opens, the copy doesn't execute. When I step through in debug, it works as expected. Does anyone see any obvious errors?
'Must have reference to "Microsoft Scripting Runtime" checked
Dim fso As New FileSystemObject
Dim wsData as Worksheet
Dim stPDFName As String
Dim stFileName As String
Dim stReport As String
Dim WSCopy As Worksheet
Dim FD As Office.FileDialog
Set wsData = ThisWorkbook.Sheets("Sheet1")
Set FD = Application.FileDialog(msoFileDialogFilePicker)
FD.InitialFileName = "J:\Laboratory\Reports\2015"
FD.Show
stReport = FD.SelectedItems(1)
stFileName = fso.GetFileName(stReport)
stPDFName = Left$(stReport, InStrRev(stReport, ".") - 1) & ".pdf"
If Dir(stPDFName) = "" Then
MsgBox "Matching PDF version of this report does not exist":
Exit Sub
Else
Workbooks.Open (stReport)
For Each WSCopy In Workbooks(stFileName).Worksheets
If StrComp(WSCopy.CodeName, "Sheet1", vbTextCompare) = 0 Then
WSCopy.Range("A1", "BZ5000").Copy
wsData.Range("E2").PasteSpecial
wsData.Columns.AutoFit
Workbooks(stFileName).Close
Exit For
End If
Next WSCopy
End If
Edit: I believe that I have narrowed down the problem to the line:
If StrComp(WSCopy.CodeName, "Sheet1", vbTextCompare) = 0 Then
When I step through the routine, the StrComp evaluates properly. If I comment out the If/End If lines, the routine works as expected. I use this line to avoid problems that occur when someone moves or renames a worksheet.
If my suspicion is correct and the macro is getting ahead of itself, this should slow it down enough to execute properly. My best guess is that is is not allowing time for the value in stReport to be set, so I have put a loop there, but you may need to try moving it around. You can test to see where the macro runs away from itself by setting a bunch of breakpoints and seeing which ones allow you to successfully resume the rest of the script after stopping at, and which ones leave it broken.
I'm fairly new to DoEvents myself and I'm aware it can be CPU intensive if not used properly, so save your work before testing this just in case you need to force close.
'Must have reference to "Microsoft Scripting Runtime" checked
Dim fso As New FileSystemObject
Dim wsData as Worksheet
Dim stPDFName As String
Dim stFileName As String
Dim stReport As String
Dim WSCopy As Worksheet
Dim FD As Office.FileDialog
Set wsData = ThisWorkbook.Sheets("Sheet1")
Set FD = Application.FileDialog(msoFileDialogFilePicker)
FD.InitialFileName = "J:\Laboratory\Reports\2015"
FD.Show
Do Until Not(IsEmpty(stReport))
stReport = FD.SelectedItems(1)
DoEvents
Loop
stFileName = fso.GetFileName(stReport)
stPDFName = Left$(stReport, InStrRev(stReport, ".") - 1) & ".pdf"
If Dir(stPDFName) = "" Then
MsgBox "Matching PDF version of this report does not exist":
Exit Sub
Else
Workbooks.Open (stReport)
For Each WSCopy In Workbooks(stFileName).Worksheets
If StrComp(WSCopy.CodeName, "Sheet1", vbTextCompare) = 0 Then
WSCopy.Range("A1", "BZ5000").Copy
wsData.Range("E2").PasteSpecial
wsData.Columns.AutoFit
Workbooks(stFileName).Close
Exit For
End If
Next WSCopy
End If

VBA: Opening a worksheet by variable name

I'm intending to copy some values from a workbook which I import from a folder on my computer, from the worksheet "2015".
My code looks like this:
Sub test()
Dim myHeadings() As String
Dim p3file As String
Dim currentWb As Workbook
Dim openWb As Workbook
Dim openWs As Worksheet
Set currentWb = ActiveWorkbook
myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",")
path3 = Dir("C:\pathtofile\filename" & ".xlsx")
p3file = "C:\pathtofile\" 'Dir doesn't return path
YearNo = Year(Date)
Do While Len(path3) > 0
Set openWb = Workbooks.Open(p3file & path3)
For i = 0 To UBound(myHeadings)
Set openWs = openWb.Sheets(YearNo)
If Err.Number <> 0 Then 'Attempt to exit while loop if sheet does not exist
Exit Do
Else
'Copy a bunch of data
End if
Next i
path3 = Dir("C:\pathtofile\filename" &".xlsx")
Loop
Workbooks(openWb.name).Close
End Sub
I've debugged by making MsgBoxes inside the loop and I can conclude that the program enters the For i = ... loop, but when encountering
Set openWs = openWb.Sheets(YearNo)
gives "Subscript out of range" error. By doing MsgBoxes I've seen that Dir finds the correct file. "p3file & path3" returns the correct file including path name. I've tested adding "" around YearNo in the opening sheet code. The sheet name is called "2015" (without quotes). Does anyone have any clue regarding this?
Thanks in advance
It's because YearNo is stored as a number, and not as text.
The Sheets Collection asks for either an index number or a string containing the name of the sheet you want to open. In your case you are providing a number, so the code thinks you are asking for sheet with index 2015, hence the out of range error.
You would need to tell Excel that the 2015 you are using is text by converting the number using CStr:-
Set openWs = openWb.Sheets(CStr(YearNo));

Opening a workbook with VBA/macro is making it read only?

I would like my code to open a workbook (always the same one), detect the first free row, write to just two cells in that row, and then save/close the workbook. This seems like a simple problem, but the macro seems to be opening a copy of the file, and then locking it for editing.
Can you see any errors in my open code? I know that the file opens and that the row search works, but then it 1. never writes to the cells, and 2. locks the file.
Function WriteToMaster(Num, Path) As Boolean
'Declare variables
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim infoLoc As Long
Set xlApp = New Excel.Application
'Specifies where the Master Move Key is stored
Set wb = xlApp.Workbooks.Open("DOC LOCATION")
Set ws = wb.Worksheets("Sheet1")
'Loop through cells, looking for an empty one, and set that to the loan number
infoLoc = firstBlankRow(ws)
MsgBox "First blank row is " & infoLoc & ". Num is " & Num
ws.Cells(infoLoc, 1).Value = Num
ws.Cells(infoLoc, 2).Value = Path
'Save, close, and quit
wb.Save
wb.Close
xlApp.Quit
'Resets the variables
Set ws = Nothing
Set wb = Nothing
Set xlApp = Nothing
'pieces of function from http://p2p.wrox.com/vb-how/30-read-write-excel-file-using-vb6.html
End Function
Thank you again, stackoverflow <3
Do you need to open a new excel app just to open a workbook?
Can't you just do something like this:
Sub Macro1()
Dim wkb As Workbook
Workbooks.Open Filename:="\User Documents$\bob\My Documents\workbook_open_example.xlsx"
Set wkb = Workbooks("workbook_open_example.xlsx")
End Sub