How to skip code in workbook2 when closing file? - excel

My problem is when closing workbook2 I need to use code to automatically select No on a message box that pops up. This is how my code is laid out:
Workbook1 creates multiple files based on user input.
The loop in Workbook1 opens up Workbook2 and inputs data from Workbook1.
When the loop is done inputing data it closes workbook2 and a message box pops up with a Yes or No button on it.
User at this time should always select No.
Another window ask if the user would like to save and it should always be yes.
Loop continues until it has created all the files user has requested
I tried googling variations of my question but have not had much luck. Any help is much appreciated.
Dim JobName As String
Dim lngLoop As Long
Dim i As Integer
Dim Customer As String
Dim LastRow As Long
Dim iCus As Integer
Dim CompanyName As String
Dim d As Long
Dim strDir As Variant
Dim DIV As String
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim ActSheet As Worksheet
Dim ActBook As Workbook
Dim CurrentFile As Workbook
Dim NewFileType As String
Dim NewFile As String
Dim QTR_NUM As String
Dim MFG As String
Dim Job As String
Dim visitdate As Variant
Dim visitdate_text As String
Dim Quote_Request As Worksheet
Dim QTR As Workbook
Dim QTRLOG As Workbook
Dim FORM As Workbook
Dim DCSProgram As Workbook
Dim ILast As Long
Dim j As Integer
Dim k As Integer
Dim CustomerIDNum As String
Dim QTRNUM As String
Dim FolderName As String
'Creates Quote For Each MFG
For j = 0 To QTRList.ListCount - 1
Set QTRLOG = Workbooks.Open("C:\QTR LOG.xlsm")
Set QTR = Workbooks.Open("C:\QTR.xlsx")
'CODE TO INPUT DATA FROM USERFORM NEW QTR
With DCSProgram.Sheets("MFG_DATA")
ILast = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If .Cells(i, 1).Value = MFG Then
QTR.Sheets(1).Range("B7").Value = .Cells(i, 2).Value
QTR.Sheets(1).Range("B8").Value = .Cells(i, 3).Value
QTR.Sheets(1).Range("B9").Value = .Cells(i, 4).Value
QTR.Sheets(1).Range("B12").Value = .Cells(i, 5).Value
QTR.Sheets(1).Range("B13").Value = .Cells(i, 6).Value
QTR.Sheets(1).Range("B14").Value = .Cells(i, 7).Value
QTR.Sheets(1).Range("B15").Value = .Cells(i, 8).Value
End If: Next: End With
With QTRLOG.Sheets("QTR_LOG")
ILast = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If .Cells(i, 1).Value = QTR_NUM Then
.Cells(i, 2) = QTRList.List(j)
'.Cells(i, 3) = FORM.Sheets(1).Range("H11").Value
.Cells(i, 5) = JobName
.Cells(i, 8) = "OPEN"
.Cells(i, 9) = QTR.Sheets(1).Range("H9").Value
End If: Next: End With
QTRLOG.Save
QTRLOG.Close
QTR.SaveAs Filename:="C:\Users\Geoffrey\Dropbox\DCS PROGRAM\FILES\2. QUOTE REQUESTS\" & JobName & "\" _
& " DCS QTR " & QTRList.List(j) & " " & JobName & " (" & CustomerIDNum & ") " & visitdate_text & " .xlsx", _
FileFormat:=51, CreateBackup:=False, local:=True
'Code To Close File After Creating It
QTR.Close
Next j
End If
Application.ScreenUpdating = True
Call Shell("explorer.exe" & " " & "C:\Users\Geoffrey\Dropbox\DCS PROGRAM\FILES\2. QUOTE REQUESTS", vbNormalFocus)
Unload NewQTR
End Sub
When this code runs a msgbox appears from the workbook QTR. I dont want the user to have to click yes or no at this time. I want to automatically select No and continue on to the next file. This process is repeated for each MFG.
Code in QTR:
Application.ScreenUpdating = True
MSG1 = MsgBox("Are you ready to email to MFG?", vbYesNo, "EMAIL MFG")
If MSG1 = vbYes Then
'Code to create email and attached workbook as PDF
Else
Const kPath As String = "C:\"
Const kFile As String = "Users\Geoffrey\Dropbox\DCS PROGRAM\FILES\9. PROGRAM FILES\1. QUOTE REQUEST\QUOTE REQUEST LOG.xlsm"
Dim TOTALFOB As Double
Dim TOTALWC As Double
Dim Wbk As Workbook
Dim INWBK As Workbook
Dim QTR_NUM As String
Dim ILast As Long
Dim i As Long
Dim TOTMFG As Variant
Dim TOTWC As Variant
Dim LR As Long
Dim TOTALTIME As Variant
Set INWBK = ThisWorkbook
With Sheets("QTR")
LR = .Range("I" & Rows.Count).End(xlUp).Row
TOTALFOB = WorksheetFunction.Sum(.Range("I23:I" & LR))
End With
TOTALWC = TOTALFOB + INWBK.Sheets("QTR").Range("D18").Value
QTR_NUM = INWBK.Sheets("QTR").Range("H7").Value
TOTALTIME = INWBK.Sheets("WS_LOG").Range("J3").Value
Rem Set Wbk in case it's open
On Error Resume Next
Set Wbk = Workbooks(kFile)
On Error GoTo 0
Rem Validate Wbk
If Wbk Is Nothing Then Set Wbk = Workbooks.Open(kPath & kFile)
With Workbooks("QUOTE REQUEST LOG.xlsm").Sheets("QTR_LOG")
ILast = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If .Cells(i, 1).Value = QTR_NUM Then
.Cells(i, 6) = TOTALFOB
.Cells(i, 7) = TOTALWC
.Cells(i, 10) = TOTALTIME
End If: Next: End With
Wbk.Save
Wbk.Close
End If
End Sub

If your problem is avoiding some Workbook_BeforeClose() event handler placed in "ThisWorkbook" code to be executed, then you must "enclose" the code lines that close the workbook like follows
Application.EnableEvents = False
' your code that closes the workbook
Application.EnableEvents = True

Exit Sub before end if is making the code exit earlier.
So remove the above mentioned one and check.

Related

Access Run-time error '91' when working with Excel

I know this has been raised many times (often under Run-time error '1004') but I am having difficulties isolating the error in my code - despite extensive research both here and other sites. My code runs from a command button on an Access form and runs successfully the first time after opening the form, but fails on subsequent attempts. I think I am using inadequate references and/or opening a second Excel object but I can't work out how.
Other formatting is carried out, but I have removed as much as possible to keep it short.
Private Sub cmdExport_Click()
Dim dbs As Database
Dim rst As DAO.Recordset
Dim appExcel As Excel.Application
Dim wbk As Excel.Workbook
Dim wks As Excel.Worksheet
Dim lngCount As Long
Dim lngDataRows As Long
Dim intLoop As Integer
Dim strSheetName As String
Dim dteStart As Date
Dim dteEnd As Date
Dim curStartBal As Currency
Dim intMoves As Integer
Dim lngCol As Long
Dim lngRow As Long
Dim intField As Integer
Dim intFieldCount As Integer
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim blnFileCheck As Boolean
strFile = "BudgetForecast.xlsx"
strPath = genFindFolder("tblSettings") 'provides path to data store
strPathFile = strPath & strFile
blnFileCheck = genDeleteFile(strPath, strFile) 'Deletes existing file if it exists
dteStart = DateAdd("m", 1, Date)
dteEnd = DateAdd("m", 12, Date)
strSheetName = "Forecast " & MonthName(Month(dteStart), True) & " " & CStr(Year(dteStart)) 'Start Month and Year
strSheetName = strSheetName & " To " & MonthName(Month(dteEnd), True) & " " & CStr(Year(dteEnd)) 'Add End Month and Year
curStartBal = [Forms]![frmBudForecast]![txtStart1]
'Create new Excel Workbook and add data
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("qryBudForecastFinal")
Set appExcel = New Excel.Application
Set wbk = appExcel.Workbooks.Add
Set wks = wbk.ActiveSheet
appExcel.Visible = True
With wks
.Name = strSheetName
.Cells(1, 1).Value = "Sort"
.Cells(1, 2).Value = "Date"
.Cells(1, 3).Value = "Type"
.Cells(1, 4).Value = "Account"
.Cells(1, 5).Value = "Payee/Details"
.Cells(1, 6).Value = "Jan"
' lines for Feb to Nov removed to shorten extract
.Cells(1, 17).Value = "Dec"
.Cells(1, 18).Value = "Totals"
rst.MoveLast
rst.MoveFirst
lngCount = rst.RecordCount
intFieldCount = rst.Fields.Count
lngDataRows = lngCount + 5
rst.MoveFirst
Do Until rst.EOF
lngCol = 1
lngRow = .[A65536].End(3).Row + 1
For intField = 0 To intFieldCount - 1
.Cells(lngRow, lngCol) = rst.Fields(intField).Value
lngCol = lngCol + 1
Next intField
rst.MoveNext
Loop
'Shift columns around to correct order
If Month(Date) <> 12 Then 'If December, records are already in correct order
intMoves = Month(Date)
For intLoop = 1 To intMoves
.Columns("R:R").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove '###Error here
.Columns("F:F").Select
Selection.Cut Destination:=Columns("R:R")
.Columns("F:F").Select
Selection.Delete Shift:=xlToLeft
Next intLoop
End If
End With
'Save new file (next line commented-out for testing)
'appExcel.ActiveWorkbook.SaveAs FileName:=strPathFile, ConflictResolution:=xlOtherSessionChanges
'Close Excel
appExcel.ActiveWindow.Close (False)
'Cleanup
rst.Close
Set rst = Nothing
Set dbs = Nothing
Set wks = Nothing
Set wbk = Nothing
appExcel.Quit 'Not sure if this line is necessary
Set appExcel = Nothing
End Sub
Error occurs on this line:
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
and 'Selection' appears to be 'Nothing'.
I've tried all sorts of variations and amendments to the syntax - I suspect I need to be more specific with the selection of column R, but I don't know how. Incidentally, when the code fails, column R on the spreadsheet is selected.
I'm tempted just to hide the command button on the form after it has been clicked, but fear this would be a cop-out and certainly wouldn't help my understanding.
appExcel.Selection
Selection is not part of the Access object model. But you should try to avoid using select/activate where possible. For example:
.Columns("F:F").Select
Selection.Delete Shift:=xlToLeft
would be better written as:
.Columns("F:F").Delete Shift:=xlToLeft
How to avoid using Select in Excel VBA

Outlook Email Body to Excel

I am trying to have the body of all emails in a folder output to an excel file. The below code is what I am using:
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim strSheet As String
Dim strPath As String
Dim intRowCounter As Integer
Dim intColumnCounter As Integer
Dim msg As Outlook.MailItem
Dim nms As Outlook.NameSpace
Dim fld As Outlook.MAPIFolder
Dim itm As Object
strSheet = "Test.xlsm"
strPath = "C:user\Documents\Action Items\"
strSheet = strPath & strSheet
Debug.Print strSheet
'Select export folder
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
'Open and activate Excel workbook.
Set appExcel = CreateObject("Excel.Application")
appExcel.Workbooks.Open (strSheet)
Set wkb = appExcel.ActiveWorkbook
Set wks = wkb.Sheets(1)
wks.Activate
appExcel.Application.Visible = True
'Copy field items in mail folder.
For Each itm In fld.Items
intColumnCounter = 1
Set msg = itm
intRowCounter = intRowCounter + 1
Set rng = wks.Cells(intRowCounter, intColumnCounter)
rng.Value = msg.Body
intColumnCounter = intColumnCounter + 1
Next itm
The issue is that each message is being put into a single cell when I want each line in outlook to have its own line in excel as if I were to copy and paste the body from outlook to excel manually (using ctrl+a, ctrl+c, ctrl+v, for example).
I feel like I need to use Split() to parse the body, but I've had no experience with that function and can't seem to get it to work.
EDIT:
I was able to solve this by using the below:
Sub SplitTextColumn()
Dim i As Long
Dim vA As Variant
[A1].Select
Range(Selection, Selection.End(xlDown)).Select
For i = 1 To Selection.Rows.Count
vA = Split(Selection.Resize(1).Offset(i - 1), vbLf)
Selection.Offset(i - 1).Resize(1, UBound(vA) + 1).Offset(, 1) = vA
Next
[A1].CurrentRegion.Offset(0, 1).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
End Sub
And
Sub MakeOneColumn()
Dim vaCells As Variant
Dim vOutput() As Variant
Dim i As Long, j As Long
Dim lRow As Long
If TypeName(Selection) = "Range" Then
If Selection.Count > 1 Then
If Selection.Count <= Selection.Parent.Rows.Count Then
vaCells = Selection.Value
ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)
For j = LBound(vaCells, 2) To UBound(vaCells, 2)
For i = LBound(vaCells, 1) To UBound(vaCells, 1)
If Len(vaCells(i, j)) > 0 Then
lRow = lRow + 1
vOutput(lRow, 1) = vaCells(i, j)
End If
Next i
Next j
Selection.ClearContents
Selection.Cells(1).Resize(lRow).Value = vOutput
End If
End If
End If
Dim c As Range
Set rng = ActiveSheet.Range("A1:A5000")
For dblCounter = rng.Cells.Count To 1 Step -1
Set c = rng(dblCounter)
If c.Value Like "*MEADWESTVACO SUMMARY 856*" Then
c.EntireRow.Insert
End If
Next dblCounter
But I don't feel like I have the excel objects referenced quite right as those subs are being called from outlook VBA. I get an error exactly every other time I run it. That is to say I can run it once, it will work, but then the second time it will break, then the third it will work again. Any suggestions?
An example is the 'SplitEmByLine' function below, I left the ReturnString and PrintArray functions in for some clarity, but these can essentially be ignored.
Sub callSplitFunction()
Dim FileFull As String, a() As String, s As Long
FileFull = "C:\Users\thomas.preston\Desktop\ThisBookOfMine.txt"
'The below line calls function
a = SplitEmByLine(ReturnString(FileFull))
PrintArray a
End Sub
'*****The below function is what you need*****
Function SplitEmByLine(ByVal Body As String) As String()
Dim x As Variant
x = Split(Body, vbCrLf)
SplitEmByLine = x
End Function
Sub PrintArray(ByRef Arr() As String)
With Sheets("Sheet1")
For i = 0 To UBound(Arr)
.Cells(i + 1, 1).Value = Arr(i)
Next i
End With
End Sub
Function ReturnString(FilePath As String) As String
Dim TextFile As Integer
Dim FileContent As String
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
Close TextFile
ReturnString = FileContent
End Function

Trying to find data in a second workbook using VBA

I have a workbook where I am building an automated e-mail but I want that e-mail to contain data that is stored in a second workbook. Please see my code below, I did change some variable names/data just for confidentiality so hopefully that doesn't make it too difficult to read.
Option Explicit
Sub Button1_Click()
Dim objExcel As Object
Dim wb1 As Workbook
Dim ws1 as Worksheet
Set objExcel = CreateObject("Excel.Application")
Set wb1 = objExcel.Workbooks.Open(ThisWorkbook.Path & "\wb1.xls")
Set ws1 = wbStoreList.Worksheets("Sheet1")
Dim filePaths As Variant
Dim msg As String
Dim i As Integer
Dim objApp As Object
Dim objMail As Object
Dim fileName As String
Dim emailAddress As String
Dim subject As String
Dim name As String
Dim otherName As String
Dim rowNumber As Range
Set objApp = CreateObject("Outlook.Application")
filePaths = Application.GetOpenFilename(MultiSelect:=True)
If (IsArray(filePaths)) Then
For i = LBound(filePaths) To UBound(filePaths)
Set objMail = objApp.CreateItem(olMailItem)
fileName = Dir(filePaths(i))
If (Len(fileName) = 8) Then
emailAddress = "email" & Mid(fileName, 1, 3) & "#emailaddress.ca"
ElseIf (Len(fileName) = 9) Then
emailAddress = "email" & Mid(fileName, 1, 4) & "#emailaddress.ca"
End If
subject = "Confidential"
With ws1
'On Error Resume Next
Set rowNumber = .Range(.Cells(8, 1), .Cells(8, 10000)).Find(What:="311", LookIn:=xlValues).Row
End With
MsgBox rowNumber
dataFound:
objMail.Recipients.Add emailAddress
objMail.subject = subject
objMail.Attachments.Add filePaths(i)
objMail.Body = name & ", " & "(" & otherName & ")" & vbNewLine & vbNewLine & "Please see attached file."
objMail.Display
Next i
Else
MsgBox "No files were selected"
End If
End Sub
The error is on the line with:
Set rowNumber = .Range(.Cells(8, 1), .Cells(8, 10000)).Find(What:="311", LookIn:=xlValues).Row
Not sure if you can directly get the row number like that because rowNumber is a Range (according to your dim statement). Give it a try and break it down into two lines:
Set rowNumber = .Range(.Cells(1, 8), .Cells(10000, 8)).Find(What:="311", LookIn:=xlValues)
and then
If Not rowNumber is Nothing then lngNumber = rowNumber.Row
Note that I am using a new variable which should be of type long.
Dim lngRowNumber as Long
By the way: in your case Integer would actually suffice over Long.

Getting error 1004 on my output range. Need to specify it correctly

I have a worksheet with the following data on it:
A B C D E
SF15-100 MFG1 JOB1 TOTALMFG TOTALWC
SF15-101 MFG2 JOB1
SF15-102 MFG3 JOB1
Im trying to write a loop to go thru column A and determine if that value is the same on a different workbook in a specific range.If its the same then it needs to paste values to the right of it in columns D and E.
i.e If
INWBK.Sheets("QTR").Range("H7").Value = "SF15-101"
Then
A B C D E
SF15-100 MFG1 JOB1 TOTALMFG TOTALWC
SF15-101 MFG2 JOB1 TOTALFOB TOTALWC
SF15-102 MFG3 JOB1
This is what I have tried so far:
Private Sub OKBTN_Click()
Dim TOTALFOB As String
Dim TOTALWC As String
Dim wbk As Workbook
Dim INWBK As Excel.Workbook
Dim TOTMFG As Variant
Dim TOTWC As Variant
Dim QTR_NUM As String
Dim ILast As Long
Dim i As Long
TOTALFOB = RefEdit1
TOTALWC = RefEdit2
Set INWBK = ActiveWorkbook
Set wbk = Workbooks.Open("C:\QUOTE REQUEST LOG 2015.xlsm")
QTR_NUM = INWBK.Sheets("QTR").Range("H7").Value
ILast = wbk.Sheets("QTR_LOG").Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If Cells(i, 1).Value = QTR_NUM Then
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 4) = TOTALFOB
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 5) = TOTALWC
Else
End If
Next i
ThisWorkbook.Save: ThisWorkbook.Saved = True
Unload Me
ActiveWorkbook.Close
End Sub
I get errors on:
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 4) = TOTALFOB
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 5) = TOTALWC
Run-time error '1004': Application-defined or object-defined error
No values were update as the workbook to be compared though declared was not used as the Cells(I,1) in this line was not qualified so the procedure was using whatever worksheet was active.
This is your code modified, please try and let me know about the results...
I assigned some values to RefEdit1 and RefEdit2 for testing
Private Sub OKBTN_Click()
Const kPath As String = "C:\"
Const kFile As String = "QUOTE REQUEST LOG 2015.xlsm"
Dim TOTALFOB As double
Dim TOTALWC As double
Dim Wbk As Workbook
Dim INWBK As Workbook
'Dim TOTMFG As Variant ' Not Used
'Dim TOTWC As Variant ' Not Used
Dim QTR_NUM As String
Dim ILast As Long
Dim i As Long
Dim RefEdit1, RefEdit2 'Not declared before
'Values Assigned for testing
TOTALFOB = 450
TOTALWC = 500
' TOTALFOB = RefEdit1
' TOTALWC = RefEdit2
Set INWBK = ThisWorkbook
Rem Set Wbk in case it's open
On Error Resume Next
Set Wbk = Workbooks(kFile)
On Error GoTo 0
Rem Validate Wbk
If Wbk Is Nothing Then Set Wbk = Workbooks.Open(kPath & kFile)
QTR_NUM = INWBK.Sheets("QTR").Range("H7").Value
With Wbk.Sheets("QTR_LOG")
ILast = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If .Cells(i, 1).Value = QTR_NUM Then
.Cells(i, 4) = TOTALFOB
.Cells(i, 5) = TOTALWC
End If: Next: End With
INWBK.Save: INWBK.Saved = True
'Unload Me
Wbk.Close SaveChanges:=True
End Sub
Suggest to visit these pages:
Excel Objects, If...Then...Else Statement, On Error Statement
Range Object (Excel), Variables & Constants, With Statement
Do let me know of any question you might have about the code and resources used.
You miss row and column index in Cells function
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 4) = TOTALFOB
wbk.Sheets("QTR_LOG").Range(Cells).Offset(0, 5) = TOTALWC
Const kPath As String = "C:\"
Const kFile As String = "QUOTE REQUEST LOG 2015.xlsm"
Dim TOTALFOB As Variant
Dim TOTALWC As String
Dim Wbk As Workbook
Dim INWBK As Workbook
Dim QTR_NUM As String
Dim ILast As Long
Dim i As Long
Dim TOTMFG As Variant
Dim TOTWC As Variant
Dim LR As Long
Set INWBK = ThisWorkbook
With Sheets("QTR")
LR = .Range("I" & Rows.Count).End(xlUp).Row
TOTALFOB = WorksheetFunction.Sum(.Range("I23:I" & LR))
End With
'Values Assigned for testing
' TOTALFOB = 450
' TOTALWC = 500
TOTALWC = TOTALFOB + INWBK.Sheets("QTR").Range("D18").Value
QTR_NUM = INWBK.Sheets("QTR").Range("H7").Value
Rem Set Wbk in case it's open
On Error Resume Next
Set Wbk = Workbooks(kFile)
On Error GoTo 0
Rem Validate Wbk
If Wbk Is Nothing Then Set Wbk = Workbooks.Open(kPath & kFile)
With Wbk.Sheets("QTR_LOG")
ILast = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To ILast
If .Cells(i, 1).Value = QTR_NUM Then
.Cells(i, 6) = TOTALFOB
.Cells(i, 7) = TOTALWC
End If: Next: End With
'INWBK.Save: INWBK.Saved = True
'Unload Me
'Wbk.Close SaveChanges:=True
End If
End Sub

Search for matching terms across two workbooks, then copy information if found

This code is for updating client information in my source document for a mail merge from a list that I can pull from my client server at any time.
I've hit a snag in this code near the end. The process it currently goes through is as follows:
user selects the merge document that needs to be updated
user selects the list with the updated addresses
code steps through the merge document, grabs the name of a company, then
searches through the second document for that company, copies the address information from the list, and
pastes it next to the company name in the merge document and
starts over with the next company name in the merge document
I'm currently stuck between steps four and five.'
here's a selection of the code I'm trying to adapt to search the source workbook, but I think this isn't going to work - I need to paste the found term into the macro workbook, and I have a gap in my knowledge of VBA here.
I can post my full code if necessary, but I didn't want to throw the whole thing in right away.
Thanks in advance!
Set sourcewkb = ActiveWorkbook
Dim rnnng As Range
Dim searchfor As String
Debug.Print celld
searchfor = celld
Set rnnng = Selection.Find(what:=searchfor)
If rnnng Is Nothing Then
Debug.Print "yes"
Else
Debug.Print "no"
End If
EDIT
I tried some of what was suggested in the comment, but I'm having an issue where the selection.find is finding the variable in question whether or not it's actually there. I think somehow it's searching in both workbooks?
Full code (some parts are marked out as notes for convenience during editing the code, they generally aren't the parts I'm concerned about):
UPDATED full code:
Sub addressfinder()
Dim rCell
Dim rRng As Range
Dim aftercomma As String
Dim celld As String
Dim s As String
Dim indexOfThey As Integer
Dim mrcell As Range
Dim alreadyfilled As Boolean
Dim nocompany As Boolean
Dim sourcewkb
Dim updaterwkb
Dim fd As FileDialog
Dim cellstocopy As Range
Dim cellstopaste As Range
Dim x As Byte
'select updater workbook
updaterwkb = "L:\Admin\Corporate Books\2015\letter macro\Annual Consent Letter Macro.xlsm"
'this is the finished updater workbook selecter.
' Set fd = Application.FileDialog(msoFileDialogFilePicker)
'
'
' Dim vrtselecteditem As Variant
' MsgBox "select the Annual Consent Letter Macro workbook"
'
' With fd
' If .Show = -1 Then
' For Each vrtselecteditem In .SelectedItems
'
'
' updaterwkb = vrtselecteditem
' Debug.Print updaterwkb
' Next vrtselecteditem
' Else
' End If
' End With
'select file of addresses
sourcewkb = "L:\Admin\Corporate Books\2015\letter macro\source workbook_sample.xlsx"
'this is the finished source select code
' Dim lngcount As Long
' If MsgBox("Have you gotten this year's updated contact list exported from Time Matters or Outlook?", vbYesNo, "confirm") = vbYes Then
' If MsgBox("Is the information in that excel workbook formatted per the instructions?", vbYesNo, "Confirm") = vbYes Then
' MsgBox "Good. Select that workbook now."
' Else
' MsgBox "Format the workbook before trying to update the update list"
' End If
' Else
' MsgBox "Have someone export you a client list with company name, client name, and client address"
'
' End If
'
'
' With Application.FileDialog(msoFileDialogOpen)
' .AllowMultiSelect = False
' .Show
' For lngcount = 1 To .SelectedItems.Count
' Debug.Print .SelectedItems(lngcount)
' sourcewkb = .SelectedItems(lngcount)
'
' Next lngcount
' End With
'
Workbooks.Open (sourcewkb)
'start the code
Set updaterwkb = ActiveWorkbook
Set rRng = Sheet1.Range("a2:A500")
For Each rCell In rRng.Cells
'boolean resets
alreadyfilled = False
nocompany = False
'setting up the step-through
s = rCell.Value
indexOfThey = InStr(1, s, ",")
aftercomma = Right(s, Len(s) - indexOfThey + 1)
celld = Left(s, Len(s) - Len(aftercomma))
Debug.Print rCell.Value, "celld", celld
Debug.Print "address", rCell.Address
'setting up already filled check
Set mrcell = rCell.Offset(rowoffset:=0, ColumnOffset:=6)
Debug.Print "mrcell", mrcell.Value
If Len(rCell.Formula) = 0 Then
Debug.Print "company cell sure looks empty"
nocompany = True
End If
If Len(mrcell.Formula) > 0 Then
Debug.Print "mrcell has content"
alreadyfilled = True
Else: Debug.Print "mrcell has no content"
End If
If alreadyfilled = False Then
If nocompany = False Then
'the code for copying stuff
'open source document
'search source document for contents of celld
'if contents of celld are found, copy everything to the right of the cell in which
'they were found and paste it horizontally starting at mrcell
'if not, messagebox "address for 'celld' not found
'Set sourcewkb = ActiveWorkbook
'
'Dim rnnng As Range
'Dim searchfor As String
'Debug.Print celld
'searchfor = celld
'
'Set rnnng = Selection.Find(what:=searchfor)
'If Not rnnng Is Nothing Then
' Debug.Print "yes"
' Else
' Debug.Print "no"
'
'End If
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim company As String
Dim lastRow As Long
Dim rng As Variant
Dim llc As String
Dim inc As String
Dim searchfor As String
Set wb1 = ThisWorkbook
Set wb2 = Workbooks("source workbook_sample.xlsx") 'change workbook name
Set ws1 = ThisWorkbook.Worksheets(1) 'change worksheet #
Set ws2 = wb2.Worksheets(1) 'change worksheet #
llc = ",LLC"
inc = ",INC."
'lastRow = ws1.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
With ws1
For i = 1 To 500
If Cells(i, 1).Value = searchfor Then
company = .Cells(i, 1)
With ws2
'change range as necessary
Set f = .Range("A1:D100").Find(company, LookIn:=xlValues)
If Not f Is Nothing Then
Debug.Print searcfor
fRow = f.Row
rng = .Range("B" & fRow & ":D" & fRow)
ws1.Range("B" & i & ":D" & i) = rng
End If
End With
End If
Next
End With
'
Else
Debug.Print "skipped cuz there ain't no company"
End If
Else
Debug.Print "skipped cuz it's filled"
End If
''
'
Debug.Print "next"
Next rCell
End Sub
fixed code:
With ws1
For i = 1 To 500
If Cells(i, 1).Value = searchfor Then
company = .Cells(i, 1)
With ws2
'change range as necessary
Set f = .Range("A1:D100").Find(company, LookIn:=xlValues)
If Not f Is Nothing Then
Debug.Print searcfor
fRow = f.Row
rng = .Range("B" & fRow & ":D" & fRow)
ws1.Range("B" & i & ":D" & i) = rng
End If
End With
End If
Next
End With
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim company As String
Dim lastRow As Long
Dim rng As Variant
Dim llc As String
Dim inc As String
Dim searchfor As String
Set wb1 = ThisWorkbook 'Annual Consent Letter Macro
Set wb2 = Workbooks("source workbook_sample.xlsx")
Set ws1 = ThisWorkbook.Worksheets(1)
Set ws2 = wb2.Worksheets(1)
llc = ",LLC"
inc = ",INC."
With ws1
For i = 1 To 500
If Cells(i, 1).Value = searchfor Then
company = .Cells(i, 1)
With ws2
'change range as necessary
Set f = .Range("A1:A500").Find(company, LookIn:=xlValues)
If Not f Is Nothing Then
Debug.Print searcfor
fRow = f.Row
rng = .Range("B" & fRow & ":D" & fRow)
ws1.Range("B" & i & ":D" & i) = rng
End If
End With
End If
Next
End With
End Sub

Resources