Finding a phrase in a string variable - excel

I am trying to find a phrase inside of a variable that contains html. I then want to replace it with a new phrase.
I tried InStr but the phrase is not found. I also tried using wildcards at tht beginning and end of the phrase. I also tried doing an if like also with and without wildcards.
The purpose is to allow a tester to do a batch change on expected results and/or test steps by entering a sentence or phrase they want changed.
The only problem I'm having is being able to programmatically find the sentence within the variable.
Problem area is in bold
Dim qcURL As String
Dim qcID As String
Dim qcPWD As String
Dim qcDomain As String
Dim qcProject As String
Dim preActVal As String
Dim postActVal As String
Dim FindSt As String
Dim currentString As String
Dim thisSheet As Worksheet
'Toggle debugging mode'
Dim isDebugOn As Boolean
isDebugOn = True 'set to true to turn off Active X
''On Error GoTo ErrHandler:
FOLDER_PATH = "BAT\PC2P - Claims - Med"
Set thisSheet = ThisWorkbook.Sheets("ShellUpdater")
TestID = thisSheet.Range("B1").Value
stField = thisSheet.Range("B2").Value
**FindSt = thisSheet.Range("B3").Value**
ReplaceSt = thisSheet.Range("B4").Value
testLocation = thisSheet.Range("B5").Value
'ActiveX Forms
If isDebugOn = False Then
'qcURL = GetOptionMetric("qcURL", 1, "Enter ALM URL") ''popup to get url from user
qcURL = "<<URL>>"
'qcDomain = GetOptionMetric("qcDomain", 1, "Enter your ALM Domain")
''popup to get domain from user
qcDomain = "<<DOMAIN>>"
'qcProject = GetOptionMetric("qcProject", 1, "Enter your ALM Project")
''popup to get project from user
qcProject = "<<PROJECT>>"
qcID = GetOptionMetric("qcID", 1, "Enter your ALM MSID")
qcPWD = GetOptionPassword("qcPWD", 1, "Enter your ALM Password")
Else
qcURL = "<<URL>>"
qcID = "<<USERNAME>>"
qcDomain = "<<DOMAIN>>"
qcProject = "<<PROJECT>>"
qcPWD = InputBox("THIS IS IN DEEBUG MODE")
If qcPWD = vbNullString Then Exit Sub
If qcPWD = "" Then Exit Sub
End If
'END ActiveX Forms
'Connect to ALM
Set tdConnection = CreateObject("TDApiOle80.TDConnection")
tdConnection.InitConnectionEx qcURL
tdConnection.Login qcID, qcPWD
tdConnection.Connect qcDomain, qcProject
''Check if batch updating or single case
Dim testObject As ITest
If InStr(TestID, "All") > 0 Then
Dim TestFact As testFactory
Set tMng = tdConnection.TreeManager
Set srcFolder = tMng.NodeByPath("Subject\" & testLocation)
Set tstFact = srcFolder.testFactory
Set tstList = tstFact.NewList("")
For Each shellTest In tstList
Set DSFact = shellTest.DesignStepFactory.NewList("")
For Each dStep In DSFact
Select Case stField
Case "StepExpectedResult"
**currentString = dStep.StepExpectedResult**
**stposition = InStr(currentString, FindSt)**
If stposition > 0 Then
dStep.StepExpectedResult = preActVal & Replace(currentString, FindSt, ReplaceSt) & postActVal
End If
Case "StepDescription"
currentString = dStep.StepDescription
stposition = InStr(currentString, FindSt)
If stposition > 0 Then
dStep.StepDescription = preActVal & Replace(currentString, FindSt, ReplaceSt) & postActVal
End If
End Select
dStep.Post
Next dStep
Next shellTest
Else
Dim myTest
'Find the Test in test plan
Set thisTest = GetTest(Trim(TestID), testLocation, "\")
Set myTest = tdConnection.testFactory.Item(TestID)
End If

Try this:
Sub replace_string()
FindSt = "but also need rendering provider first name"
ReplaceString = "I LIKE BANANAS"
currentString = "All fields populate from the correctly populated provider<<<\!Renderingproviderlastname>>>, but also need rendering provider first name"
stPosition = Replace(currentString, FindSt, ReplaceString)
MsgBox stPosition
End Sub

Related

How to get PO with each SIZE/EAN breakdown on ITEM level?

QUESTION
I'm using VBA for retrieving data from SAP via BAPI. What RFC should I use, and how, to retrieve PO details at the "each SIZE for each ITEM" level.
EXAMPLE
In this screenshot you see that the PO includes 3 ITEMs. Each of these ITEMs includes several SIZEs/EANs. And for each of the SIZEs/EANs, the specific QUANTITIES are indicated
I want to retrieve this data into Excel. So I create all the needed objects for working with SAP, connect to BAPI_PO_GETITEMS, fill in PURCHASEORDER-parameter, indicate the table PO_ITEMS:
Option Explicit
Public Functions As SAPFunctionsOCX.SAPFunctions
Private LogonControl As SAPLogonCtrl.SAPLogonControl
Private objConnection As SAPLogonCtrl.Connection
Dim Func As SAPFunctionsOCX.Function
Public eNUMBER_OF_ENTRIES As SAPFunctionsOCX.Parameter
Public tENTRIES As SAPTableFactoryCtrl.Table
Public TableFactory As SAPTableFactory
Sub BAPI_PO_GETDETAIL()
Dim i As Integer, j As Integer
Dim retcd As Boolean
Dim SilentLogon As Boolean
Set LogonControl = CreateObject("SAP.LogonControl.1")
Set Functions = CreateObject("SAP.Functions")
Set TableFactory = CreateObject("SAP.TableFactory.1")
Set objConnection = LogonControl.NewConnection
SilentLogon = True
'Use the below block to hardcode system connection and connect automatically
objConnection.Client = ""
objConnection.ApplicationServer = ""
objConnection.Language = ""
objConnection.User = ""
objConnection.Password = ""
objConnection.System = ""
objConnection.SystemNumber = ""
'Logging into SAP
If objConnection.Logon(0, SilentLogon) Then
'Logon was successful
MsgBox "Logged on!"
'Create an object to call the RFC FM
Functions.Connection = objConnection
'Actual FM is added here
Set Func = Functions.Add("BAPI_PO_GETITEMS")
'Populate the importing parameters
Func.Exports("PURCHASEORDER").Value = "2845158864"
'Indicate the TABLE needed
Set tENTRIES = Func.Tables("PO_ITEMS")
'Call FM
Func.Call
'Dump onto the worksheet
For i = 1 To tENTRIES.ColumnCount 'cells(R, C)
cells(1, i).Value = tENTRIES.ColumnName(i)
Next i
For i = 1 To tENTRIES.RowCount
For j = 1 To tENTRIES.ColumnCount
cells(i + 1, j).Value = tENTRIES.Value(i, j)
Next j
Next i
Else
MsgBox "Not Logged on"
End If
End Sub
and get only 3 rows - for each of the 3 ITEMS, without the breakdown by SIZE/EAN:
How to retrieve the breakdown by SIZE/EAN, like on this screenshot:

How to show thumbnail of a dwg-File in a excel VBA Userform

I want to write a little DMS to tag and save ACAD files. For this i am using Excel VBA. Using with ACAD 2014 / 2015 / 2019.
Step 1 - save drawing:
When copy some parts of the drawing, there is a copy in %temp% and something like a WindowsMetaFile (WMF) in clipboard.
Here i grab the copy from %temp%.
Step 2 - load file to ACAD:
With serching or filtering i can load theese files as block into ACAD.
By filtering, a listbox show the different tags.
Also i wan´t to show a Thumnail of the ACAD file in a Imagebox. But it doesn´t work.
Problem:
How to show thumnail from dwg´s in userform?
I think there is more than one solution. However I do not know how.
Solution 1:
In Step1: Copy WMF from Clipboard and save to file. Maybe as jpg or png?!?
In Step2: Load Image or WMF from File and show in Imagebox.
Solution 2:
In Step 1: Create a Thumbnail of the dwg.
In Step 2: Load Thumbnail to Imagebox.
Solution 3:
DWG TrueView Control
https://through-the-interface.typepad.com/through_the_interface/2007/10/au-handouts-t-1.html
Need a registration. But only have Acad student version.
Solution 4:
AutoCAD DwgThumbnail Control
https://forums.augi.com/showthread.php?42906-DWG-Block-Preview-Image
But there isn´t a "DwgThumbnail.ocx" file
'Step 1 - it works
Private Sub cmdSpeichern_Click()
'Spaltentitel
Dim SpalteID, SpalteBeschreibung, SpalteDatum, SpalteHäufigkeit, SpalteSystemhersteller, SpalteSystem, SpalteElement, SpalteEinbaulage As String
SpalteID = 1
SpalteDatum = 2
SpalteBeschreibung = 3
SpalteHäufigkeit = 4
SpalteSystemhersteller = 5
SpalteSystem = 6
SpalteElement = 7
SpalteEinbaulage = 8
Dim Pfad, teil
Dim Dateiname As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
Dim NewestFile As String
Dim lngZeile As Long
Dim WindowsBenutzername As String
WindowsBenutzername = VBA.Environ("UserName")
Pfad = "C:\Users\" & WindowsBenutzername & "\AppData\Local\Temp\"
teil = "A$"
Dateiname = Dir(Pfad & teil & "?????????.DWG")
If Dateiname <> "" Then
MostRecentFile = Dateiname
MostRecentDate = FileDateTime(Pfad & Dateiname)
Do While Dateiname <> ""
If FileDateTime(Pfad & Dateiname) > MostRecentDate Then
MostRecentFile = Dateiname
MostRecentDate = FileDateTime(Pfad & Dateiname)
End If
Dateiname = Dir
Loop
End If
NewestFile = MostRecentFile
'MsgBox NewestFile
'Datei kopieren
Dim myFSO As Object
Dim qFolder As String, tFolder As String
Dim qFile As String
qFile = NewestFile
qFolder = Pfad
tFolder = ThisWorkbook.Path & "\dwg\"
Set myFSO = CreateObject("Scripting.FileSystemObject")
myFSO.copyfile qFolder & qFile, tFolder & qFile, True
'Datei umbenennen
Name tFolder & NewestFile As tFolder & Tabelle2.Cells(1, 2) & ".dwg"
'Infos in Excel einragen
lngZeile = 3
Do Until Tabelle1.Cells(lngZeile, 1) = ""
lngZeile = lngZeile + 1
Loop
If Tabelle1.Cells(lngZeile + 1, 1) = "" Then
Tabelle1.Cells(lngZeile, SpalteID) = Tabelle2.Cells(1, 2)
Tabelle1.Cells(lngZeile, SpalteDatum) = Now ' Format
Tabelle1.Cells(lngZeile, SpalteBeschreibung) = txtBeschreibung.Value
Tabelle1.Cells(lngZeile, SpalteHäufigkeit) = "0"
Tabelle1.Cells(lngZeile, SpalteSystemhersteller) = cboSystemhersteller
Tabelle1.Cells(lngZeile, SpalteSystem) = cboSystem.Value
Tabelle1.Cells(lngZeile, SpalteElement) = cboElement.Value
'Tabelle1.Cells(lngZeile, SpalteEinbaulage) = cboEinbaulage.Value
End If
'ID erhöhen
Tabelle2.Cells(1, 2) = Tabelle2.Cells(1, 2) + 1
'Datei abspeichern
ThisWorkbook.Save
'Fertigmeldung
MsgBox "Zeichnung erfolgreich gespeichert."
End Sub
'Step 2 - It´s not final, but works
Private Sub CommandButton3_Click()
Dim insertionPnt(0 To 2) As Double
inserationPnt = AutoCAD.Application.ActiveDocument.Utility.GetPoint(, "Einfügepunkt wählen: ")
Dim BlockRef As AcadBlockReference
'Runden
inserationPnt(0) = Round(inserationPnt(0), 0)
inserationPnt(1) = Round(inserationPnt(1), 0)
inserationPnt(2) = 0
insertionPnt(0) = inserationPnt(0): insertionPnt(1) = inserationPnt(1): insertionPnt(2) = inserationPnt(2)
FileToInsert = ThisWorkbook.Path & "\dwg\10.dwg"
Set BlockRef = AutoCAD.Application.ActiveDocument.ModelSpace.InsertBlock(insertionPnt, FileToInsert, 1#, 1#, 1#, 0)
End Sub
How to say it nicely :) Doesnt work that easy. "In Trough the Interface" is a article how to generate a block thumbnail. Thumbnails genration
You may also try to store WMF files from a block and convert them - VBA sample downstairs. But thats also not really nice. There is stupidly no ready to use API to fetch all Block images by VBA nor by .NET. There might be some expensive DWG reading libs out. But i would wrap a modified Version of Kens block into a vba callable DLL and act with her (there are c# to vba converters out ). At all nothing that easy but will work. And just to mention. That will not be that fast in any case. If the block images are not already generated this will take time.And how to store them in the excel file ? Might be a idea to put them in a database as a blob and use some database connectors. All at all a nightmare.
Sub BlockPreview(blockname As Variant, imageControlName As Variant, UserForm As UserForm)
'
' Biolight - 2008
' http://biocad.blogspot.com/
' Biolightant(at)gmail.com
'
Dim blockRefObj As AcadBlockReference
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = -10000000000000#: insertionPnt(1) = -10000000000000#: insertionPnt(2) = 0
' Insert Block
Set blockRefObj = ThisDrawing.modelspace.InsertBlock(insertionPnt, blockname, 1#, 1#, 1#, 0)
Dim minPt As Variant
Dim maxPt As Variant
blockRefObj.GetBoundingBox minPt, maxPt
minPt(0) = minPt(0) - 2
minPt(1) = minPt(1) - 2
maxPt(0) = maxPt(0) + 2
maxPt(1) = maxPt(1) + 2
' Block Zoom
ZoomWindow minPt, maxPt
ThisDrawing.REGEN acActiveViewport
'ThisDrawing.Regen True
' Make SelectionSets
Dim FType(0 To 1) As Integer, FData(0 To 1)
Dim BlockSS As AcadSelectionSet
On Error Resume Next
Set BlockSS = ThisDrawing.SelectionSets("BlockSS")
If ERR Then Set BlockSS = ThisDrawing.SelectionSets.Add("BlockSS")
BlockSS.CLEAR
FType(0) = 0: FData(0) = "INSERT": FType(1) = 2: FData(1) = blockname
BlockSS.Select acSelectionSetAll, , , FType, FData
' Block Export image(wmf)
ThisDrawing.Export ThisDrawing.PATH & "\" & blockname, "wmf", BlockSS
BlockSS.ITEM(0).DELETE
BlockSS.DELETE
ThisDrawing.applicaTION.UPDATE
' ZoomPrevious
applicaTION.ZoomPrevious
' UserForm image control picture = block.wmf
UserForm.CONTROLS(imageControlName).Picture = LoadPicture(ThisDrawing.PATH & "\" & blockname & ".wmf")
UserForm.CONTROLS(imageControlName).PictureAlignment = fmPictureAlignmentCenter
UserForm.CONTROLS(imageControlName).PictureSizeMode = fmPictureSizeModeZoom
' Delete block.wmf file
Dim fs, F, F1, FC, s
Set fs = CreateObject("Scripting.FileSystemObject")
Set F = fs.getfolder(ThisDrawing.PATH)
Set FC = F.FILES
For Each F1 In FC
If F1.NAME = blockname & ".wmf" Then
F1.DELETE
End If
Next
On Error GoTo 0
End Sub

Not able to get out of the loop after getfirstitem in lotus script

Sub Initialize
On Error GoTo ErrorOut
Dim sess As NotesSession
Dim db As NotesDatabase
Dim doc, searchDoc, reqNumDoc As NotesDocument
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim stream As NotesStream
Dim vwSearchRequests As NotesView
Dim reqNum, totalNotify, totalAccepted, totalRejected, totalOOO, totalNoRes As Integer
Dim reqSer, reqJRSS, reqSPOC, reqNumStr As String
Dim reqDate As String
Dim reqNumColl As NotesDocumentCollection
Dim reqPanelRes As NotesItem
Dim reqPanelResValue As Variant
Set sess = New NotesSession
Set db = sess.CurrentDatabase
Set vwSearchRequests = db.GetView("RequestDocReport")
vwSearchRequests.Autoupdate = False
Set searchDoc = vwSearchRequests.GetFirstDocument
While Not searchDoc Is Nothing
reqSer = "Service"
reqJRSS = searchDoc.PS_JRSS(0)
reqSPOC = "Hiring SPOC"
totalAccepted = 0
totalRejected = 0
totalOOO = 0
totalNoRes = 0
totalNotify = 0
reqNum = searchDoc.PS_RequestNo(0)
reqNumStr = {PS_RequestNo = "} & reqNum & {"}
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNumStr)
Set reqNumDoc = reqNumColl.GetFirstDocument
While Not reqNumColl Is Nothing
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
MsgBox CStr(reqPanelResValue(0))
'Exit Sub
If CStr(reqPanelResValue(0)) = "Accepted" Then
totalAccepted = totalAccepted + 1
End If
If CStr(reqPanelResValue(0)) = "Rejected" Then
totalRejected = totalRejected + 1
End If
If CStr(reqPanelResValue(0)) = "OOO" Then
totalOOO = totalOOO + 1
End If
Else
If CStr(reqPanelResValue(0)) = "" Then
totalNoRes = totalNoRes + 1
End If
End If
totalNotify = totalNotify + 1
Set reqNumDoc = reqNumColl.GetNextDocument(reqNumDoc)
Wend
what is the error in code? The code is getting stuck after
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
Instead of line
While Not reqNumColl Is Nothing
write
While Not reqNumDoc Is Nothing
You got an infinitive loop because the collection reqNumColl is not nothing all the time even when you reached the last document in collection. Instead you have to test the document reqNumDoc.
Another issue might be your code for collection calculation:
reqNumStr = {PS_RequestNo = "} & reqNum & {"}
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNumStr)
The way you coded it the first sorted column in view should contain
PS_RequestNo = "12345"
Probably, your view contains in first sorted column just the request number. If so, your code would be just:
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNum)
if column contains a numeric value or
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(cStr(reqNum))
if it contains a string.
Apart from any other problems you might have in your code (and #Knut is correct about the cause of your infinite loop), this is not a good pattern:
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
You're retrieving the item twice when you don't actually have to.
This woould be much better:
If reqNumDoc.HasItem"PanelResponse") Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")

How to finda text and get the page no. for acrobat using vba

I want to find the text and get the page number of text found in acrobat using VBA, I am able to find the text but not able to get the page number. for that
Sub Main()
Dim acrApp, acrAVDoc
Set acrApp = CreateObject("AcroExch.app")
Set acrAVDoc = CreateObject("AcroExch.AVDoc")
acrApp.Show
If acrAVDoc.Open("FileName", "") Then
Ok = acrAVDoc.FindText("Text to search", 0, 1, 1)
MsgBox (Ok)
End If
Set acrAVDoc = Nothing
Set acrApp = Nothing
End Sub
I am not able to set the object for
Set acrPDDoc = CreateObject("Acrobat.AV_PAGE_VIEW")
I know this is an old question, but it was one of the top search results when I was looking for the same info. I never found anything that truly met my needs so I made something up by combining several different resources.
The function below is acceptably fast, even on very large documents. It searches page by page, not word by word, so it will find multi-word matches and words with dashes (case insensitive). It returns the matches for all pages separated by commas.
Hope this is helpful to someone in the future.
Sub Demo()
Dim SearchResult As String
SearchResult = AdobePdfSearch("my search string", "C:\Demo\Demo.pdf")
MsgBox SearchResult
End Sub
Function AdobePdfSearch(SearchString As String, strFileName As String) As String
'Note: A Reference to the Adobe Library must be set in Tools|References!
'Note! This only works with Acrobat Pro installed on your PC, will not work with Reader
Dim AcroApp As CAcroApp, AcroAVDoc As CAcroAVDoc, AcroPDDoc As CAcroPDDoc
Dim AcroHiliteList As CAcroHiliteList, AcroTextSelect As CAcroPDTextSelect
Dim PageNumber, PageContent, Content, i, j, iNumPages
Dim strResult As String
Set AcroApp = CreateObject("AcroExch.App")
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
If AcroAVDoc.Open(strFileName, vbNull) <> True Then Exit Function
Set AcroPDDoc = AcroAVDoc.GetPDDoc
iNumPages = AcroPDDoc.GetNumPages
For i = 0 To iNumPages - 1
Set PageNumber = AcroPDDoc.AcquirePage(i)
Set PageContent = CreateObject("AcroExch.HiliteList")
If PageContent.Add(0, 9000) <> True Then Exit Function
Set AcroTextSelect = PageNumber.CreatePageHilite(PageContent)
' The next line is needed to avoid errors with protected PDFs that can't be read
On Error Resume Next
For j = 0 To AcroTextSelect.GetNumText - 1
Content = Content & AcroTextSelect.GetText(j)
Next j
If InStr(1, LCase(Content), LCase(SearchString)) > 0 Then
strResult = IIf(strResult = "", i + 1, strResult & "," & i + 1)
End If
Content = ""
Next i
AdobePdfSearch = strResult
'Uncomment the lines below if you want to close the PDF when done.
'AcroAVDoc.Close True
'AcroApp.Exit
'Set AcroAVDoc = Nothing: Set AcroApp = Nothing
End Function
sub checks each page of pdf, word by word
Sub FindtextandPageNumber()
Dim FindWord 'Word you want to search
Dim acroAppObj As Object
Dim PDFDocObj As Object
Dim myPDFPageHiliteObj As Object
Dim iword As Integer, iTotalWords As Integer
Dim numOfPage As Integer, Nthpage As Integer
Dim word As String, sPath As String
Set acroAppObj = CreateObject("AcroExch.App")
Set PDFDocObj = CreateObject("AcroExch.PDDoc")
Set myPDFPageHiliteObj = CreateObject("AcroExch.HiliteList")
Check3 = myPDFPageHiliteObj.Add(0, 32767)
FindWord = "Hello"
acroAppObj.Show
sPath = "Test.pdf" 'Path of pdf where you want to search
PDFDocObj.Open (sPath)
numOfPage = PDFDocObj.GetNumPages
word = vbNullString
Set PDFJScriptObj = Nothing
For Nthpage = 0 To numOfPage - 1
Set pAcroPDPage = PDFDocObj.AcquirePage(Nthpage)
Set wordHilite = pAcroPDPage.CreateWordHilite(myPDFPageHiliteObj)
Set PDFJScriptObj = PDFDocObj.GetJSObject
iTotalWords = wordHilite.GetNumText
iTotalWords = PDFJScriptObj.getPageNumWords(Nthpage)
''check the each word
For iword = 0 To iTotalWords - 1
word = Trim(CStr(PDFJScriptObj.getPageNthWord(Nthpage, iword)))
If word <> "" Then
If word = FindWord Then
PageNumber = Nthpage
msgbox PageNumber
End If
word = ""
End If
Next iword
Next Nthpage
End Sub

For Loop Being Skipped Over

I have not been able to figure out why the For Loop block (with two for loops) is being skipped over by the code. I know it's being skipped bc a message box is being tripped further down in the code. Any thoughts?
Dim OL As Outlook.Application
Dim myitem As Outlook.MailItem
Dim wb As Workbook
Dim ws As Worksheet
Dim PicPath As String
Dim x, y As Integer
Dim Name As Name
Dim cell, rng1 As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
wb.Sheets("Sheet1").Activate
'Request type check
If (Sheet1.NewResource.Value = False) And (Sheet1.Modification.Value = False) Then
MsgBox "Please select a Request Type of your request and complete the other mandatory fields"
GoTo cont
End If
'checking New Resource Entry mandatory fields
If Sheet1.NewResource.Value = True Then
If (Sheet1.NewPOnobx.Value = False) And (Sheet1.NewPOyesbx.Value = False) Then
MsgBox "Please fill the missing mandatory fields"
GoTo cont
End If
If (Sheet1.POyesbx.Value = False) And (Sheet1.POnobx.Value = False) Then
MsgBox "Please fill the missing mandatory fields"
GoTo cont
End If
If (Sheet1.POnobx.Value = True) And (Sheet1.SOWtxt.Value = "") Then
MsgBox "Please select a copy of the Signed Agreement"
GoTo cont
End If
For Each Name In ActiveWorkbook.Names 'each named range in gateway fields
If (Name = "C_LN") Or (Name = "C_FN") Or (Name = "C_SD") Or (Name = "C_ED") Or (Name = "C_O") Or (Name = "C_D") Or (Name = "C_OF") Or (Name = "C_C") Or (Name = "C_M") Or _
(Name = "C_R") Or (Name = "C_PT") Or (Name = "C_V") Or (Name = "C_SAR") Or (Name = "C_BAR") Or (Name = "C_SR") Or (Name = "C_SS") Or (Name = "C_PO") Then 'all gateway field names
x = 0
For Each cell In Name 'cell in the named range
If cell.Value = "" Then 'looking for blank mandatory fields
If (cell.Name = "LN_Cmt") Or (cell.Name = "FN_Cmt") Or (cell.Name = "SD_Cmt") Or (cell.Name = "ED_Cmt") Or (cell.Name = "O_Cmt") Or _
(cell.Name = "D_Cmt") Or (cell.Name = "OF_Cmt") Or (cell.Name = "C_Cmt") Or (cell.Name = "M_Cmt") Or (cell.Name = "R_Cmt") Or _
(cell.Name = "PT_Cmt") Or (cell.Name = "V_Cmt") Or (cell.Name = "SAR_Cmt") Or (cell.Name = "BAR_Cmt") Or (cell.Name = "SR_Cmt") Or _
(cell.Name = "SS_Cmt") Or (cell.Name = "PO_Cmt") Then
GoTo skip1
Else
x = x + 1 '+1 for a blank mandatory field
End If
End If
skip1:
Next cell
If x > 0 Then 'flag the missing info
MsgBox "Please fill the missing mandatory fields"
GoTo cont
End If
End If
Next Name
End If
For me, the Name in the for loop gives something like =Sheet1!$G$2:$G$5 ... this doesn't match your C_R or whatever. I need to use Name.Name to get that. And then to get the range of cells for the name, I need to use Name.RefersToRange.
Also, to make your If list easier to manage, you could use Select Case instead:
Select Case Name.Name
Case "C_LN", "C_FN", "C_SD", "C_ED", "C_O", "C_D", "C_OF", "C_C", "C_M", "C_R", "C_PT", "C_V", "C_SAR", "C_BAR", "C_SR", "C_SS", "C_PO"
For Each cell In Name.RefersToRange
Debug.Print cell.Address
Next cell
Case Else
Debug.Print "Other Name"
End Select
Don't use name it is a reserved word (you can rename files with Name File1 as File2).
Change the variable name to MyName or something similar then if you continue to experience the issue, put a stop on the code and evaluate the loop manually in the debug wind (CTRL-G) by typing ?activeworkbook.Names.Count and pressing enter (don't forget the ?) and see if you have a number above zero.

Resources