Related
Here is a question i have for importing data from Access to Excel.
So first I need to write data from Excel to Access (when the data is saved in Access, the data are saved as the access units by doing a unit conversion of the data from Excel).
After that, I may want to recall these data back into excel and the excel needs to convert the recalled data back into the base units of Excel.
That being said, for cells with money values, I assign these cells with a unit type of CURRENCY. When these data is saved in Access, they become $. But when they are recalled back into Excel, the base unit in excel is M$. I need to figure out a coding that let these cells value divided by 1000 so they become M$ in Excel. After that, I will have a droplist that let me convert these values to either $ or MM$ when i want to. The conversions for bbl and mcf are already done by original user.
Not sure if anyone can give me a easy solution for this...I have the code below:
Set rs2 = db.OpenRecordset("SELECT * FROM Project_Data WHERE LoadID = " & _
record_ID & " ORDER BY LoadID Asc", dbReadOnly)
For v = 1 To 1244
v_name = vars(v, 1)
If vars(v, 2) = "Y" Then
rs2.MoveFirst
Do
If rs2![VariableName] = v_name Then ' And rs2![LoadID] = record_ID Then
If Mid(v_name, 1, 2) = "T1" Then
Sheets("T1").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T2" Then
Sheets("T2").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T3" Then
Sheets("T3").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T4" Then
Sheets("T4").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T5" Then
Sheets("T5").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T6" Then
Sheets("T6").Range(v_name) = Val(rs2![VariableValue])
End If
If Mid(v_name, 1, 2) = "T7" Then
Sheets("T7").Range(v_name) = Val(rs2![VariableValue])
End If
Exit Do
End If
rs2.MoveNext
Loop Until rs2.EOF
End If
Next v
rs2.Close
Set rs2 = Nothing
db.Close
Set db = Nothing
Unload Me
write_log ("Imported existing record.")
Sheets("Main").Range("GASUNITS") = "MMcf"
ThisWorkbook.gas_units = "MMcf"
Sheets("Main").Range("LIQUIDUNITS") = "Mbbl"
ThisWorkbook.liquid_units = "Mbbl"
Call Switch_Liquids_Units("Mbbl")
Call Switch_Gas_Units("MMcf")
MsgBox ("Data has been loaded.")
End Sub
Coding for switch_Liquids_Units:
Sub Switch_Liquids_Units(units)
If Range("LIQUIDUNITS") = "Mbbl" Then
pass_unit = "M"
pass_fluid = "Oil"
End If
If Range("LIQUIDUNITS") = "MMbbl" Then
pass_unit = "MM"
pass_fluid = "Oil"
End If
If Range("LIQUIDUNITS") = "bbl" Then
pass_unit = ""
pass_fluid = "Oil"
End If
Call Replace_Units(pass_unit, pass_fluid)
Sheets("Main").Select
If do_old = True Then
Sheets("T1").Select
'Rows("3:3").Select
Range("B3:AE3").Select
If units = "bbl" Then
Selection.Replace What:="(Mbbl)", Replacement:="(bbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMbbl)", Replacement:="(bbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(Mboe)", Replacement:="(boe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMboe)", Replacement:="(boe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
If units = "Mbbl" Then
Range("B3:AE3").Replace What:="(bbl)", Replacement:="(Mbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMbbl)", Replacement:="(Mbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(boe)", Replacement:="(Mboe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMboe)", Replacement:="(Mboe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
If units = "MMbbl" Then
Selection.Replace What:="(bbl)", Replacement:="(MMbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(Mbbl)", Replacement:="(MMbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(boe)", Replacement:="(MMboe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(Mboe)", Replacement:="(MMboe)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
Sheets("T2").Select
'Rows("4:4").Select
Range("B4:AN4").Select
If units = "bbl" Then
Selection.Replace What:="(Mbbl)", Replacement:="(bbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMbbl)", Replacement:="(bbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
If units = "Mbbl" Then
Selection.Replace What:="(bbl)", Replacement:="(Mbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(MMbbl)", Replacement:="(Mbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
If units = "MMbbl" Then
Selection.Replace What:="(bbl)", Replacement:="(MMbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(Mbbl)", Replacement:="(MMbbl)", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
End If
End Sub
To answer your titled question (unable to help with posted code), simply adjust SQL query for the needed conversion. Below shows how the SQL statement can be conditionally modified by needed units conversion. Integrate the below in appropriate sections of your code base. Also, avoid SELECT *. Instead, explicitly define columns for code readability and maintainability.
If unitVariable = "per thousand"
strSQL = "SELECT Col1 / 1E3 As Col1_in_thousands, " & _
" Col2 / 1E3 As Col2_in_thousands, " & _
" Col3 / 1E3 As Col3_in_thousands, " & _
" ... " & _
" FROM Project_Data " & _
" WHERE LoadID = " & record_ID & _
" ORDER BY LoadID ASC"
ElseIf unitVariable = "per million"
strSQL = "SELECT Col1 / 1E6 As Col1_in_millions, " & _
" Col2 / 1E6 As Col2_in_millions, " & _
" Col3 / 1E6 As Col3_in_millions, " & _
" ... " & _
" FROM Project_Data " & _
" WHERE LoadID = " & record_ID & _
" ORDER BY LoadID ASC"
ElseIf unitVariable = "per billion"
strSQL = "SELECT Col1 / 1E9 As Col1_in_billions, " & _
" Col2 / 1E9 As Col2_in_billions, " & _
" Col3 / 1E9 As Col3_in_billions, " & _
" ... " & _
" FROM Project_Data " & _
" WHERE LoadID = " & record_ID & _
" ORDER BY LoadID ASC"
End If
' PASS DYNAMIC SQL QUERY
Set rs2 = db.OpenRecordset(strSQL, dbReadOnly)
...
Aside: since MS Access is a database, you should be storing the most detailed precision of data in it and since Excel is an end-use reporting tool (not to be used for persistent data storage), simply convert to whatever units needed at the report side and in this case via the SQL query.
I have a set of data which only pulls as MMM-DD-YYYY. I'd like to convert it to a date (MM/DD/YYYY format) to look it up versus another set of data.
I recorded a macro to simply replace the months with their respective numbers individually but I know there has to be a better way to do this. Below is my
current code:
With ws1.Cells
.Replace What:="jan-", Replacement:="01-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="feb-", Replacement:="02-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="mar-", Replacement:="03-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="apr-", Replacement:="04-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="may-", Replacement:="05-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="jun-", Replacement:="06-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="jul-", Replacement:="07-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="aug-", Replacement:="08-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="sep-", Replacement:="09-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="oct-", Replacement:="10-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="nov-", Replacement:="11-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:="dec-", Replacement:="12-", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End With
This will convert your text string into a true date for the active cell:
Sub datefix()
Dim s As String
s = ActiveCell.Value
arr = Split(s, "-")
ActiveCell.Value = arr(1) & " " & arr(0) & " " & arr(2)
End Sub
You can format it or loop it to your heart's content.
(I am using US locale)
EDIT#1:
With your desired format:
Sub datefix()
Dim s As String
s = ActiveCell.Value
arr = Split(s, "-")
ActiveCell.Value = arr(1) & " " & arr(0) & " " & arr(2)
ActiveCell.NumberFormat = "mm/dd/yyyy"
End Sub
Before:
and after:
Good morning,
I have an Excel document that is set up to complete a mail merge. Previously, a ran a script from within the MS Word mail merge template to call the Excel file, connect to it, and pull in the data. I recently found a code example that suggested embedding the code within the Excel document and pointing it to the Word template. This seems to make a lot more sense given my workflow.
This snippet worked within MS Word to reach out and connect to the Excel workbook:
ThisDocument.MailMerge.OpenDataSource Name:= _
ThisDocument.Path & "\" & "REF 1.23.18.xlsm", ConfirmConversions:=False, _
ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=reflist.xlsm;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:Database Locking " _
, SQLStatement:="SELECT * FROM `REF_LTR$`", SQLStatement1:="", SubType:= _
wdMergeSubTypeAccess
However, when I move the script over into MS Excel to try and connect to the Word template from Excel, this script is failing with a "run time error 4198 - Command Failed":
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
ConfirmConversions:=False, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `REF_LTR$`", SQLStatement1:="", SubType:= _
wdMergeSubTypeAccess
Any suggestions on what my second block of code is missing?
Here is the entire script for reference:
Sub test()
' Delete the first 8 rows which contain the header data
On Error Resume Next
Rows("1:8").Select
Selection.Delete Shift:=xlUp
' Delete the empty spaces in column A, Name
Columns("A:A").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' Delete the empty spaces in column B, MRN
Columns("B:B").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' Delete the empty spaces in columns D and E, format them as dates
Columns("D:E").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.NumberFormat = "m/d/yyyy"
' Delete the empty spaces in columns F and G
Columns("F:G").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' Format AdmitTime as military time
Columns("F:F").Select
Application.CutCopyMode = False
Selection.NumberFormat = "h:mm;#"
Selection.NumberFormat = "hhmm"
' Delete any rows that don't have a name in column A
Columns("A").SpecialCells(xlBlanks).EntireRow.Delete
' Add the column titles
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("1:1").Select
Selection.Font.Bold = True
Selection.Font.Underline = xlUnderlineStyleSingle
Range("A1").Select
ActiveCell.FormulaR1C1 = "Name"
Range("B1").Select
ActiveCell.FormulaR1C1 = "MRN"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Sex"
Range("D1").Select
ActiveCell.FormulaR1C1 = "DOB"
Range("E1").Select
ActiveCell.FormulaR1C1 = "AdmitDate"
Range("F1").Select
ActiveCell.FormulaR1C1 = "AdmitTime"
Range("G1").Select
ActiveCell.FormulaR1C1 = "Category"
Range("H1").Select
ActiveCell.FormulaR1C1 = "ReferHospital"
Range("I1").Select
ActiveCell.FormulaR1C1 = "Complaint"
Range("J1").Select
ActiveCell.FormulaR1C1 = "Description"
Range("K1").Select
ActiveCell.FormulaR1C1 = "Unit"
Range("L1").Select
ActiveCell.FormulaR1C1 = "Disposition"
Range("M1").Select
ActiveCell.FormulaR1C1 = "LOS"
Range("N1").Select
ActiveCell.FormulaR1C1 = "ICD10"
Range("O1").Select
ActiveCell.FormulaR1C1 = "AdmitYear"
Range("P1").Select
ActiveCell.FormulaR1C1 = "AdmitMonth"
Range("Q1").Select
ActiveCell.FormulaR1C1 = "AdmitDay"
Range("R1").Select
ActiveCell.FormulaR1C1 = "GenderPronoun"
Range("A2").Select
' Add the helper columns to pull in the admityear, admitmonth, admitday, and genderpronoun
Range("O2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-14]="""","""",TEXT(RC[-10],""yyyy""))"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-14]="""","""",TEXT(RC[-10],""yyyy""))"
Range("P2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-15]="""","""",TEXT(RC[-11],""mm""))"
Range("Q2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-16]="""","""",TEXT(RC[-12],""dd""))"
Range("R2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-17]="""","""",IF(RC[-15]=""M"",""his"",""her""))"
Range("O2:R2").Select
Selection.Copy
Range("O3:R50").Select
ActiveSheet.Paste
' Find and replace hospital names
Columns("H:H").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' Fort Hamilton Hospital
Columns("H:H").Select
Cells.Replace What:="FortHamilton-HughesMemorialHospital(", Replacement _
:="Fort Hamilton Hospital", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Grandview
Columns("H:H").Select
Cells.Replace What:="GrandviewHospital(OHMontgomery)", Replacement _
:="Grandview Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Greene Memorial Hospital
Columns("H:H").Select
Cells.Replace What:="GreeneMemorialHospital(OHGreene)", Replacement _
:="Greene Memorial Hospital", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Kettering Health Network - Franklin
Columns("H:H").Select
Cells.Replace What:="FRANKLINSPRINGBOROED", Replacement _
:="Kettering Health Network - Franklin", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Kettering Health Network - Huber
Columns("H:H").Select
Cells.Replace What:="HuberHeightsED", Replacement _
:="Kettering Health Network - Huber", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Kettering Health Netowrk - Preble
Columns("H:H").Select
Cells.Replace What:="PrebleCoED", Replacement _
:="Kettering Health Network - Preble", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' McCullough-Hyde Memorial Hospital
Columns("H:H").Select
Cells.Replace What:="McCullough-HydeMemorialHospital(OH", Replacement _
:="McCullough-Hyde Memorial Hospital", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Mercer County Community Hospital
Columns("H:H").Select
Cells.Replace What:="MercerCountyJointTwp.CommunityHospi", Replacement _
:="Mercer County Community Hospital", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Soin Medical Center
Columns("H:H").Select
Cells.Replace What:="SoinMedicalCenter", Replacement _
:="Soin Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Southview Medical Center
Columns("H:H").Select
Cells.Replace What:="SouthviewHospital&FamilyHealthCente", Replacement _
:="Southview Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Springfield Regional Medical Center
Columns("H:H").Select
Cells.Replace What:="CommunityHospitalofSpringfield(OHCl", Replacement _
:="Springfield Regional Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Columns("H:H").Select
Cells.Replace What:="SpringfieldRegionalHosptial", Replacement _
:="Springfield Regional Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Sycamore Medical Center
Columns("H:H").Select
Cells.Replace What:="SycamoreHospital(OHMontgomery)", Replacement _
:="Sycamore Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Upper Valley Medical Center
Columns("H:H").Select
Cells.Replace What:="UpperValleyMedicalCenter", Replacement _
:="Upper Valley Medical Center", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Wilson Memorial Hospital
Columns("H:H").Select
Cells.Replace What:="WilsonHospital(OHShelby)", Replacement _
:="Wilson Memorial Hospital", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
' Select A1 cell
Range("A1").Select
' This macro does the following:
' Runs a mail merge and pulls fields to create follow-up letter drafts
' Creates individual Word documents and then saves them in the appropriate folder for the hospital name
'
Dim Name As String
Dim MRN As String
Dim Sex As String
Dim DOB As String
Dim AdmitDate As String
Dim AdmitTime As String
Dim Category As String
Dim ReferHospital As String
Dim Complaint As String
Dim Description As String
Dim Unit As String
Dim Disposition As String
Dim LOS As String
Dim ICD10 As String
Dim AdmitYear As String
Dim AdmitMonth As String
Dim AdmitDay As String
Dim GenderPronoun As String
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
'Check to see if the folder exists, and if not, create it
Dim fdObj As Object
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists(ThisDocument.Path & ReferHospital) Then
Else
fdObj.CreateFolder (ThisDocument.Path & ReferHospital)
End If
' NEW!!!!
' Connect to the sign-in spreadsheet which is the data source
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open("C:\Users\k113997\Desktop\1macrotest\Trauma Referral Template.docm")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.CreateDataSource _
Name:=strWorkbookName, _
SQLStatement:="SELECT * FROM `REF_LTR$`", _
SubType:=wdMergeSubTypeAccess
' Obtaines the number of records from the mail merge
For i = 1 To ThisDocument.MailMerge.DataSource.RecordCount
' Counts the lines in the excel file
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = i
.LastRecord = i
.ActiveRecord = i
' Ignore any records where Name is blank, as in empty data fields
If Trim(.DataFields("Name")) = "" Then Exit For
' Pull in the datafields from the sign-in spreadsheet
Name = .DataFields("Name").Value
MRN = .DataFields("MRN").Value
Sex = .DataFields("Sex").Value
DOB = .DataFields("DOB").Value
AdmitDate = .DataFields("AdmitDate").Value
AdmitTime = .DataFields("AdmitTime").Value
Category = .DataFields("Category").Value
ReferHospital = .DataFields("ReferHospital").Value
Complaint = .DataFields("Complaint").Value
Description = .DataFields("Description").Value
Unit = .DataFields("Unit").Value
Disposition = .DataFields("Disposition").Value
LOS = .DataFields("LOS").Value
ICD10 = .DataFields("ICD10").Value
AdmitYear = .DataFields("AdmitYear").Value
AdmitMonth = .DataFields("AdmitMonth").Value
AdmitDay = .DataFields("AdmitDay").Value
GenderPronoun = .DataFields("GenderPronoun").Value
End With
' Execute the mail merge
.Execute Pause:=False
End With
' Set the directory path for the output files to be the same as the directory for this document
docpath = ThisDocument.Path & "\" & ReferHospital
' Set the document naming convention with the course year, course month, course day, department, and course name
docname = AdmitYear + "-" + AdmitMonth + "-" + AdmitDay + " " + MRN
' Check and make sure that docname does not have any special characters that will mess up the filename, and if found, remove them
docnameclean = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(docname, "<", ""), ">", ""), ":", ""), "/", ""), "\", ""), "?", ""), "&", ""), "*", ""), ",", ""), ".", "")
' Change the focus to the active directory where the files are stored
ChDrive ActiveDocument.Path
' ChangeFileOpenDirectory _
' ".\"
ActiveDocument.SaveAs2 Filename:=docpath & "\" & docnameclean + ".docx", _
FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
' Close the active document
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
' Switch to the next document in the mail merge
Next i
wd.Visible = True
wdocSource.Close SaveChanges:=False
Set wdocSource = Nothing
Set wd = Nothing
End Sub
Thanks,
Chris
When you open a Word document or attach a Template through VBA, the mail merge data source (if any) is not attached to the document for security reasons.
Try replacing:
wdocSource.MailMerge.OpenDataSource(...)
To:
wdocSource.MailMerge.CreateDataSource(...)
using the same method parameters but do not set the Connection parameter as it will be created for you.
wdocSource.MailMerge.CreateDataSource _
Name:=strWorkbookName, _
SQLStatement:="SELECT * FROM `REF_LTR$`", _
SubType:= wdMergeSubTypeAccess
i want to pop up a inputbox when LR is coming..
Look in code:
LR = Range("G" & Rows.Count).End(xlUp).Row
Range("G2:G" & LR).Select
Sub FixIt()
Dim LR As Long
LR = Range("G" & Rows.Count).End(xlUp).Row
Range("G2:G" & LR).Select
Selection.Replace What:=Chr(160), Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.NumberFormat = "0.00"
Selection.Style = "Comma"
End Sub
You can use the Application.InputBox with Type:=8 to specify an input box which will have as its return value a Range object.
Here is an example of using such an input box to get the row number of a selected cell.
Dim inRange as Range
Set inRange = Application.InputBox("Please select a cell...", Type:=8)
If Not inRange Is Nothing Then
LR = inRange.Row
Else
'Probably you want to Exit Sub here or do some error-handling
End If
Or, to use the same approach to get the entire range of selection:
Dim myRange as Range
Set myRange = Application.InputBox("Please select some range...", Type:=8)
If myRange Is Nothing Then
'Probably you want to Exit Sub here or do some error-handling
End If
'proceed with the rest of your code...
With myRange
.Replace What:=Chr(160), Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.NumberFormat = "0.00" Selection.Style = "Comma"
End With
I am, once again, stuck on something.
I am trying to clean phone numbers data, and the code isn't doing anything.
Columns(icount).Replace What:=",", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Columns(icount).Replace What:="-", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
icount is the column where the phone # are.
I don't understand why it's not working. Replacing "à" with "à" works fine.
Try Using 'LookAt:=xlPart' instead of using 'LookAt:=xlWhole'
Columns(icount).Replace What:=",", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Columns(icount).Replace What:="-", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
You could it like so:
Sub rep()
For Each c In Sheets("Sheet1").Range("A:A").Cells ' Change the range that you want
If InStr(c.Value, ",") > 0 Then
deli = Split(c, "")
For a = 0 To UBound(deli)
c.Value = replace(c.Value, ",", "")
Next a
End If
If InStr(c.Value, "-") > 0 Then
deli = Split(c, "")
For a = 0 To UBound(deli)
c.Value = replace(c.Value, "-", "")
Next a
End If
Next c
End Sub