Converting Word>Excel mail merge to an Excel>Word merge - excel

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

Related

Run-time error '5': Invalid procedure or call argument

I'm attempting to run a macro and keep getting a "run-time error '5': invalid procedure or call argument." Nothing has changed to the file nor the macro since I last used it, but I did get a new laptop. I'm not sure if this has to do with permissions in my excel or if in fact the macro is broken and needs to be fixed.
Sub SS_Cleanup()
ActiveWorkbook.RefreshAll
Sheets("report").Select
Columns("H:H").Select
Range("H:H").Activate
Selection.Replace What:="Global Equity, benchmarked to the MSCI ACWI", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:="ESG High Conviction, benchmarked to the MSCI ACWI", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:="International Conviction, benchmarked to the MSCI ACWI", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
Selection.Replace What:= _
"No Animal Testing (Medical/Pharma Allowed) Strategy benchmarked to the S", _
Replacement:= _
"No Animal Testing (Medical/Pharma Allowed) Strategy benchmarked to the S&P 1500" _
, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat _
:=False, ReplaceFormat:=False
Selection.Replace What:= _
"Gifting", _
Replacement:= _
"Not Applicable" _
, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat _
:=False, ReplaceFormat:=False
Dim i, n As Integer
Dim ProductHolder, Product As String
Dim ProductName As String
i = 2
Do While Workbooks("SS Data Converter.xlsm").Worksheets("report").Cells(i, 1) <> ""
'enters the product in last column
ProductHolder = ""
Product = ""
ProductName = ""
ProductHolder = Workbooks("SS Data Converter.xlsm").Worksheets("report").Cells(i, 8)
If ProductHolder <> "" And ProductHolder <> "Not Applicable" And ProductHolder <> "Jointly Managed" Then
Product = Right(ProductHolder, Len(ProductHolder) - InStr(ProductHolder, "S&") + 1)
**ProductName = Left(ProductHolder, InStr(ProductHolder, "Strategy") - 2)**
End If
Select Case Product
Case "S&P 1500"
The bold text above is what is saying is a problem with the macro. I haven't attempted to fix it but instead research the root cause. Thanks.

Import Data from Access to Excel and do a conversion from $ to M$

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.

How to turn multiple find and replaces into more efficient loop

Below is what I have in the middle of a bigger macro I've made. Creating loops and especially inserting them into larger macros successfully is something I don't know how to do. Any help is appreciated
F column has a header. How far the rows could be occupied is dynamic. When I made this I selected the entire column instead of offset 1 cell down control shift down to select simply because the input was small enough it didn't matter. Now the inputs are bigger and are slowing everything down.
' remove FIRST style tags from description *Add new ones here*
Sheets("Columns").Select
Columns("F:F").Select
Selection.Replace What:="<span style*>", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'2
Sheets("Columns").Select
Columns("F:F").Select
Selection.Replace What:="<div style=*>", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'3
Sheets("Columns").Select
Columns("F:F").Select
Selection.Replace What:="<p style*>", Replacement:="<p>", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
...
'18
Sheets("Columns").Select
Columns("F:F").Select
Selection.Replace What:="<tbody>", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Below is new code
Sub Sample()
Dim StartTime As Double
Dim SecondsElapsed As Double
'Remember time when macro starts
StartTime = Timer
Dim Ar(1 To 17) As String '~~> 4 to number of items
Dim i As Long
Dim Ar2(1) As String '~~> 1 to number of items
Dim a As Long
Ar(1) = "<span style*>"
Ar(2) = "<div>"
Ar(3) = "<div style=*>"
Ar(4) = "<tbody>"
Ar(5) = "</div>"
Ar(6) = "<ul style=*>"
Ar(7) = "<li style=*>"
Ar(8) = "<table style*>"
Ar(9) = "<col style*>"
Ar(10) = "<tr style=*>"
Ar(11) = "<td class=*>"
Ar(12) = "<colgroup>"
Ar(13) = "</colgroup>"
Ar(14) = "</tbody>"
Ar(15) = "</td>"
Ar(16) = "</tr>"
Ar(17) = "</table>"
For i = 1 To UBound(Ar)
Sheets("Columns").Columns(6).Replace What:=Ar(i), _
Replacement:="", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Next i
Ar2(1) = "<p style*>"
For a = 1 To UBound(Ar2)
Sheets("Columns").Columns(6).Replace What:=Ar2(a), _
Replacement:="<p>", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Next a
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
'Notify user in seconds
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub
Store all the search items in an array and then replace them in a loop. For example (UNTESTED)
Sub Sample()
Dim Ar(1 To 4) As String '~~> 4 to number of items
Dim i As Long
Ar(1) = "<span style*>"
Ar(2) = "<p style*>"
Ar(3) = "<div style=*>"
Ar(4) = "<tbody>"
For i = 1 To Ubound(Ar)
Sheets("Columns").Columns(6).Replace What:=Ar(i), _
Replacement:="", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Next i
End Sub

Error putting a variable inside excel VBA function

Sub airtableCleaner()
Dim x As Integer
Dim argCounter As Integer
Dim A As String
Dim B As String
Dim folderLocation As Variant
Dim Answer As VbMsgBoxResult
'Ask user if they want to run macro
Answer = MsgBox("Do you want to run this macro? Please use airtable Download as CSV - Column 1: Primary key, Column 2: Airtable Linkz", vbYesNo, "Run Macro")
If Answer = vbYes Then
folderLocation = Application.InputBox("Enter a folder location where your image assets will be")
'Cleanup to just amazons3 dl.airtable links
Columns("B:B").Select
Selection.Replace What:="* ", 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.Replace What:=")", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'Count Cells
Range("B2").Activate
Do
If ActiveCell.Value = "" Then Exit Do
ActiveCell.Offset(1, 0).Activate
argCounter = argCounter + 1
Loop
'Copy Image Links to new cells to format in Column C
Columns("B:B").Select
Selection.Copy
Columns("C:C").Select
ActiveSheet.Paste
Application.CutCopyMode = False
'Clean up links to only have names in Column C
Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
False, ReplaceFormat:=False
'Create Batch on Column D
Range("D2").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D9")
Range("D2:D9").Select
'Delete header row 1 information
Rows("1:1").Select
Selection.Delete Shift:=xlUp
'Repaste values back into column D removing formulas
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End If
End Sub
I have this set of excel VBA code. I'm getting an error
Run-time error '1004' Application-defined or object-defined error
At this line
"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
I have been setting folderLocation variable value as c:\doge and making a file folder reflecting this
My code was working fine until I introduced a variable inside of an excel function
What am I doing wrong here?
EDIT
this was the original formula I was using
=CONCATENATE("COPY ",CHAR(34),C5,CHAR(34)," ", CHAR(34), "c:\doge\",A5,".png",CHAR(34))
where c:\doge\ was the place I wanted to input the user input at.
Is this what you are trying?
folderLocation = "c:\doge\"
Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C5,CHAR(34),"" "", CHAR(34), " & _
Chr(34) & folderLocation & Chr(34) & ",A5,"".png"",CHAR(34))"

I want to use a inputbox e.g. to choose G:F or K:K ...look at my code:

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

Resources