How to change variables of a Word footer from Excel vba? - excel

I have several variables to be updated in a Word footer from Excel.
I am only able to change variables out of the footer.
Sub Internal_Offer()
Dim datos(1 To 100) As String
Dim reemp(1 To 100) As String
wArch = Hoja1.Range("B2").Text & Hoja1.Range("B1").Text & ".docx"
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Add Template:=wArch, NewTemplate:=False, DocumentType:=0
lenght = Hoja1.Range("B3").Value
For i = 1 To lenght - 1 'celda dónde está la cuenta
datos(i) = Hoja1.Range("A" & i + 3).Text 'dónde están los datos
reemp(i) = Hoja1.Range("B" & i + 3).Text 'dónde están las etiquetas
Next i
objWord.Activate 'Activa el documento de word
For i = 1 To lenght - 1 'celda dónde está la cuenta
With objWord.Selection.Find
.Text = datos(i) 'busca el texto de datos
.Replacement.Text = reemp(i) 'reemplaza por el texto
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2
End With
Next i
End Sub

There are at least two ways to address all footers of a Word document:
StoryRanges
Sections.Footers
Please try this (ActiveDocument is your objWord):
Private Sub CheckAllDocumentFooters()
Dim r As Word.Range
Dim s As Word.Section
Dim hf As Word.HeaderFooter
' either all story ranges:
For Each r In ActiveDocument.StoryRanges
Select Case r.StoryType
Case wdEvenPagesFooterStory, wdPrimaryFooterStory, wdFirstPageFooterStory
r.WholeStory
Debug.Print r.Text
End Select
' further sections:
While Not (r.NextStoryRange Is Nothing)
Set r = r.NextStoryRange
Select Case r.StoryType
Case wdEvenPagesFooterStory, wdPrimaryFooterStory, wdFirstPageFooterStory
r.WholeStory
Debug.Print r.Text
End Select
Wend
Next r
' or all sections:
For Each s In ActiveDocument.Sections
For Each hf In s.Footers
Debug.Print hf.Index
Debug.Print hf.Range.Text
Next hf
Next s
End Sub

Related

How can I extract data from multiple Word documents to excel rows based on keywords using VBA?

I got this VBA code from #macropod to extract data from various Word files from the folder that is in the "strFolder" variable of the VBA code below, but I can only extract data that is in front of the keyword, as in the term "TRABALHO" (attached image) the VBA code extracts the content from the front, but I can't extract data from below, for example in: "CONSTATAÇÃO" I can't extract the text from below, if anyone can help me I would appreciate it. Just below I also put a capture of the document that I have to use to extract the data.
IMAGE - Word Document
Sub GetData()
'Note: this code requires a reference to the Word object model.
'See under the VBA Editor's Tools|References.
Application.ScreenUpdating = False
Dim WkSht As Worksheet, r As Long, c As Long
Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim strFile As String, strFolder As String, strOut As String, StrFnd
strFolder = "C:\Users\" & Environ("UserName") & "\Desktop\Macro VBA - Trabalhos Sequenciais\Trabalhos\"
StrFnd = Array("", "", "TRABALHO", "SEQUENCIAL", "REGISTRO", "DATA DA IMPLEMENTAÇÃO", "PRAZO PARA EFETIVAÇÃO", _
"DATA DA EFETIVAÇÃO", "RESPONSÁVEL PELA ANÁLISE", "REVISOR", "CONSTATAÇÃO")
Set WkSht = ActiveSheet: r = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
r = r + 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
WkSht.Cells(r, 1).Value = Split(strFile, ".doc")(0)
With wdDoc
For c = 2 To UBound(StrFnd)
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Text = ""
.Forward = True
.Format = False
.MatchCase = False
.MatchWildcards = False
.Text = StrFnd(c)
.Wrap = wdFindContinue
.Execute
End With
If .Find.Found = True Then
.End = .Paragraphs(1).Range.End
.Start = .Start + Len(StrFnd(c))
strOut = Trim(Replace(Replace(Replace(Split(.Text, vbCr)(0), vbTab, " "), Chr(11), " "), Chr(160), " "))
Do While strOut = ""
.Collapse wdCollapseEnd
.MoveEnd wdParagraph, 1
strOut = Trim(Replace(Replace(Replace(Split(.Text, vbCr)(0), vbTab, " "), Chr(11), " "), Chr(160), " "))
Loop
WkSht.Cells(r, c).Value = strOut
End If
End With
Next
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub
From what I can tell, your data are in various cells in the first 3 tables in the document. In that case, you need something like:
Sub GetData()
'Note: this code requires a reference to the Word object model.
'See under the VBA Editor's Tools|References.
Application.ScreenUpdating = False
Dim WkSht As Worksheet, r As Long, c As Long
Dim wdApp As New Word.Application, wdDoc As Word.Document, wdRng As Word.Range
Dim strFile As String, strFolder As String
strFolder = "C:\Users\" & Environ("UserName") & "\Desktop\Macro VBA - Trabalhos Sequenciais\Trabalhos\"
Set WkSht = ActiveSheet: r = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
r = r + 1: c = 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
WkSht.Cells(r, c).Value = Split(strFile, ".doc")(0)
With wdDoc
With .Tables(1)
Set wdRng = .Cells(1, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(1, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(1, 3).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
End With
With .Tables(2)
Set wdRng = .Cells(1, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(1, 4).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(2, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(3, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
Set wdRng = .Cells(4, 2).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
End With
With .Tables(3)
Set wdRng = .Cells(2, 1).Range: c = c + 1
WkSht.Cells(r, c).Value = Split(Rng.Text, vbCr)(0)
End With
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
wdApp.Quit
Set wdRng = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub
I can answer how to extract data from multiple word files and write it to text file.
Following is the code to extract multiple word files from multiple folders and sub folders
import glob
import docx2txt as d2t
input_dir=r"D:\Doc scraping\xyz"
filepaths=list(glob.glob(input_dir+"\**\*.docx", recursive=True))
def extract_data_from_docx(path_to_file, get_text=False):
text = d2t.process(path_to_file)
if(get_text): #Defining a function to extract text from docx file
return text
data=""
for filepath in filepaths:
data = data + extract_data_from_docx(filepath, get_text=True)
print(data)

Assign .Find results to a variable or write it directly into the cell?

I have a problem with assigning .Find results to a variable or writing it directly into the Excel cell.
The macro (that's written and lunched from Excel) cycles through 2-5 paragraphs with customers data (in word document) - 1 customer data in every single paragraph.
When macro separates a single paragraph it then searches for info (ID number) in this paragraph only.
The search is performed using word wildcards <[A-Z]{3} [0-9]{6}> and ID number is always found.
After it's found I need to write it into ActiveSheet.Cells(x, 12)
Or I just need to assign it to a variable, but I don't know how to do this.
For Each Para In rng.Paragraphs
'get NAME
name = Trim$(Para.Range.Words(3)) 'Trim$ is the string version. Use this if you are using it on a string.
Debug.Print name
pStart = InStr(1, Para, ".") + 1 'here we get 3 'we should get 3
Length = InStr(1, Para, ",") - pStart 'here we get 22/29/27/39 - 3
'exit For Each loop when coma character is not found
If Length < 1 Then Exit For
Debug.Print Trim$(Mid(Para, pStart, Length))
name = Trim$(Mid(Para, pStart, Length))
'get PESEL
pStart = InStr(1, Para, textToFind4) + Len(textToFind4) + 1 'textToFind4 = "PESEL"
Length = InStr(pStart, Para, ",") - pStart '51-pStart = 11
Debug.Print Trim$(Mid(Para, pStart, Length))
pesel = Trim$(Mid(Para, pStart, Length))
sexDigit = Mid(pesel, 10, 1)
Debug.Print sexDigit
remainder = sexDigit Mod 2
Debug.Print remainder
x = x + 1
'Cells(x, 1).Value = Trim(Mid(Para, pStart, Length))
ActiveSheet.Cells(x, 1).Value = name
ActiveSheet.Cells(x, 4).Value = pesel
Set singleParaRng = Para.Range
Debug.Print singleParaRng
'Check if there is an ID Card and find its number
If remainder = 0 Then
'With singleParaRng.Find
With Para.Range.Find
.Text = "legitymująca się dowodem osobistym"
.MatchWildcards = False
.MatchCase = False
.Forward = True
.Execute
If .Found = True Then
mySheet.Cells(x, 11) = "dowód"
With Para.Range.Find
.Text = "<[A-Z]{3} [0-9]{6}>"
.MatchWildcards = True
.MatchCase = True
.Wrap = wdFindStop
.Forward = True
.Execute
If .Found = True Then 'here is the problem
ActiveSheet.Cells(x, 12) = Para.Range.Text 'here is the problem
End If
End With
Else
mySheet.Cells(x, 11) = "paszport"
End If
End With
Else
'With singleParaRng.Find
With Para.Range.Find
.Text = "legitymujący się dowodem osobistym"
.MatchWildcards = False
.MatchCase = False
.Forward = True
.Execute
If .Found = True Then
mySheet.Cells(x, 11) = "dowód"
Else
mySheet.Cells(x, 11) = "paszport"
End If
End With
End If
Next Para
Currently the result is that the whole paragraph is written into the ActiveSheet.Cells(x, 12) cell and I just need this wildcard ActiveSheet.Cells(x, 12) result written in.
Or assigned into a variable.
I've read this thread MS Word VBA Find and Loop (NOT Replace)
and I think the answer is somewhere there, but I can't figure it out for my own example.
I figured it out eventually - checked and working code below:
Sub FindNamesPESELsAndPriceWithInput_Finalll() 'this code works flawlessly
Application.ScreenUpdating = False
Dim wordApp As Word.Application 'it is assigned to button #2
Dim wordDoc As Word.Document '[0-9]{1;5}[ ]{1;2}/[0-9]{4}
Dim excelApp As Excel.Application
Dim mySheet As Excel.Worksheet
Dim Para As Word.Paragraph
Dim rng As Word.Range
Dim idNmbr As Word.Range
Dim singleParaRng As Word.Range
Dim fullName As Word.Range
Dim pStart As Long
Dim pEnd As Long
Dim Length As Long
Dim textToFind1 As String
Dim textToFind2 As String
Dim textToFind3 As String
Dim textToFind4 As String
Dim textToFind5 As String
Dim textToFind6 As String
Dim name As String
Dim pesel As String
Dim sexDigit As String
Dim price As Double 'Dim price As Single 'Dim price As Long
Dim remainder As Integer
Dim startPos As Long
Dim endPos As Long
Dim parNmbr As Long
Dim x As Long
Dim flag As Boolean
Dim scndRng As Range
Dim aryNum As Variant
'Assigning object variables and values
Set wordApp = GetObject(, "Word.Application") 'At its simplest, CreateObject creates an instance of an object,
Set excelApp = GetObject(, "Excel.Application") 'whereas GetObject gets an existing instance of an object.
Set wordDoc = wordApp.ActiveDocument
Set mySheet = Application.ActiveWorkbook.ActiveSheet
'Set MySheet = ExcelApp.ActiveWorkbook.ActiveSheet
Set rng = wordApp.ActiveDocument.Content
Set scndRng = ActiveSheet.Range("A10:J40").Find("cena", , xlValues)
textToFind1 = "KRS 0000511671, REGON: 147269372, NIP: 5252588142," ' "KRS 0000609737, REGON 364061169, NIP 951-24-09-783," ' "REGON 364061169, NIP 951-24-09-783,"
textToFind2 = "- ad." 'w umowach deweloperskich FW2 było "- ad."
textToFind3 = "Tożsamość stawających"
textToFind4 = "PESEL"
textToFind5 = "cenę brutto w kwocie łącznej"
textToFind6 = "cenę brutto w kwocie "
x = 11
'InStr function returns a Variant (Long) specifying the position of the first occurrence of one string within another.
startPos = InStr(1, rng, textToFind1) - 1 'here we get 1410 or 1439 or 1555, we're looking 4 "TextToFind1"
endPos = InStr(1, rng, textToFind2) - 1 'here we get 2315 or 2595 or 2207, we're looking 4 "- ad."
parNmbr = rng.Paragraphs.Count
Debug.Print "Total # of paragraphs = " & parNmbr
'Calibrating the range from which the names will be pulled
If startPos > 1 And endPos > 1 Then ' Exit Sub
rng.SetRange Start:=startPos, End:=endPos ' startPos = 0 Or endPos = 0 Or endPos = -1
Debug.Print "Paragraphs.Count = " & rng.Paragraphs.Count
Debug.Print rng
rng.MoveStart wdParagraph, 1 ' Moves the start position of the specified range.
Debug.Print "Paragraphs.Count = " & rng.Paragraphs.Count
Debug.Print rng
Else
endPos = InStr(1, rng, textToFind3) - 1 'here we get 2595 lub 2207, we're looking 4 "Tożsamość stawających"
rng.SetRange Start:=startPos, End:=endPos 'startPos = 0 Or endPos = 0 Or endPos = -1
Debug.Print "Paragraphs.Count = " & rng.Paragraphs.Count
Debug.Print rng
rng.MoveStart wdParagraph, 1
rng.MoveEnd wdParagraph, -1
Debug.Print "Paragraphs.Count = " & rng.Paragraphs.Count
Debug.Print rng
End If
If startPos <= 0 Or endPos <= 0 Then
MsgBox ("Client's names were not found!")
'Client's names input
Else
For Each Para In rng.Paragraphs
'get NAME
name = Trim$(Para.Range.Words(3)) 'Trim$ is the string version. Use this if you are using it on a string.
Debug.Print name
pStart = InStr(1, Para, ".") + 1 'here we get 3 'we should get 3
Length = InStr(1, Para, ",") - pStart 'here we get 22/29/27/39 - 3
'exit For Each loop when coma character is not found
If Length < 1 Then Exit For
Debug.Print Trim$(Mid(Para, pStart, Length))
name = Trim$(Mid(Para, pStart, Length))
'get PESEL
pStart = InStr(1, Para, textToFind4) + Len(textToFind4) + 1 'textToFind4 = "PESEL"
Length = InStr(pStart, Para, ",") - pStart '51-pStart = 11
Debug.Print Trim$(Mid(Para, pStart, Length))
pesel = Trim$(Mid(Para, pStart, Length))
sexDigit = Mid(pesel, 10, 1)
Debug.Print sexDigit
remainder = sexDigit Mod 2
Debug.Print remainder
x = x + 1
'Cells(x, 1).Value = Trim(Mid(Para, pStart, Length))
ActiveSheet.Cells(x, 1).Value = name
ActiveSheet.Cells(x, 4).Value = pesel
Set singleParaRng = Para.Range
Debug.Print singleParaRng
Set idNmbr = Para.Range
Debug.Print idNmbr
'Check if there is an ID Card and find its number
If remainder = 0 Then
With Para.Range.Find
.Text = "legitymująca się dowodem osobistym"
.MatchWildcards = False
.MatchCase = False
.Forward = True
.Execute
If .Found = True Then
mySheet.Cells(x, 11) = "dowodem osobistym"
Debug.Print Para.Range.Text 'Dim Para As Word.Paragraph
With idNmbr.Find 'Dim idNmbr As Word.Range
.Text = "<[A-Z]{3} [0-9]{6}>"
.MatchWildcards = True
.MatchCase = True
.Wrap = wdFindStop
.Forward = True
.Execute
Debug.Print idNmbr
If .Found = True Then
mySheet.Cells(x, 12) = idNmbr
End If
End With
Else
mySheet.Cells(x, 11) = "paszportem"
End If
End With
Else
With Para.Range.Find
.Text = "legitymujący się dowodem osobistym"
.MatchWildcards = False
.MatchCase = False
.Forward = True
.Execute
If .Found = True Then
mySheet.Cells(x, 11) = "dowodem osobistym"
Debug.Print Para.Range.Text 'Dim Para As Word.Paragraph
With idNmbr.Find 'Dim idNmbr As Word.Range
.Text = "<[A-Z]{3} [0-9]{6}>"
.MatchWildcards = True
.MatchCase = True
.Wrap = wdFindStop
.Forward = True
.Execute
Debug.Print idNmbr
If .Found = True Then
mySheet.Cells(x, 12) = idNmbr
End If
End With
Else
mySheet.Cells(x, 11) = "paszportem"
End If
End With
End If
Next Para
'End of client's names input
The main change comparing to the code in the question is adding a variable to store .Find result (in the very beginning of the macro).
Dim idNmbr As Word.Range
Second thing is assigning this object variable a value in this line and checking it's value using Debug.Print command.
Set idNmbr = Para.Range
Debug.Print idNmbr
Having previous declarations and assignments in place I perform .Find as follows:
With idNmbr.Find 'Dim idNmbr As Word.Range
.Text = "<[A-Z]{3} [0-9]{6}>"
.MatchWildcards = True
.MatchCase = True
.Wrap = wdFindStop
.Forward = True
.Execute
Debug.Print idNmbr
After checking the .Find result with Debug.Print idNmbr I know if I have what I expected or not.
The last two lines assign .Find results to the desired Excel cell:
If .Found = True Then
mySheet.Cells(x, 12) = idNmbr
End If
End With

Collect data from visible rows only applying manual filter

I created the macro below (my first time macro ever) to automatically generate PDFs in bulk, creating one per row populating a Word template with the corresponding fields. Now, I need to filter the data to generate PDFs only for the remaining visible rows, but cant figure out what lines of the code to modify to make this happen. I have read about the .SpecialCells(xlCellTypeVisible) but I have no idea where to use it nor if it is even the way to go. I would greatly appreciate some help. Thanks!
Sub PrintPrivacyPolicyDoc_EN()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim objWord As Word.Application, wdDoc As Word.Document
Dim datos(0 To 1, 0 To 9) As String
Set a = Sheets(ActiveSheet.Name)
nom = ActiveWorkbook.Name
pto = InStr(nom, ".")
nomarch = Left(nom, pto - 1)
wArch = ThisWorkbook.Path & "\" & a.Range("B3").Text & ".dotx"
uf = a.Range("A" & Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
uf = a.Range("A" & Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
For j = 5 To uf
Set wdDoc = objWord.Documents.Open(wArch)
nomfic = nomarch & "_" & a.Cells(j, "A") & "_" & a.Range("C3").Text
rutainf = ThisWorkbook.Path & "\" & "PrivacyPolicy PDFs" & "\" & nomfic & ".pdf"
'Variables to find and text to substitute"
datos(0, 0) = "[Company_Name]"
datos(1, 0) = a.Cells(j, "B")
datos(0, 1) = "[Vat_Number]"
datos(1, 1) = a.Cells(j, "C")
datos(0, 2) = "[URL_Stay]"
datos(1, 2) = a.Cells(j, "D")
datos(0, 3) = "[Update_Date]"
datos(1, 3) = a.Cells(j, "E")
For I = 0 To UBound(datos, 2)
textobuscar = datos(0, I)
objWord.Selection.Move 6, -1
objWord.Selection.Find.Execute FindText:=textobuscar
While objWord.Selection.Find.Found = True
objWord.Selection.Text = datos(1, I) 'texto a reemplazar
objWord.Selection.Move 6, -1
objWord.Selection.Find.Execute FindText:=textobuscar
Wend
Next I
'Search for the file and delete it before saving the newest verion
If Dir(rutaInf) <> "" Then
Kill rutaInf
End If
'Save file with the designated name
wdDoc.SaveAs Filename:=rutaInf, FileFormat:=wdFormatPDF
'Close Word template without saving changes
wdDoc.Close savechanges:=False
MsgBox ("PDF files were successfully generated"), vbInformation, "NOTIFICATION"
wdDoc.Quit
End Sub
Untested:
Sub PrintPrivacyPolicyDoc_EN()
Dim objWord As Word.Application, wdDoc As Word.Document
Dim nomArch As String, uf As Long, wArch As String
Dim ws As Worksheet, j As Long, nomFic As String, rutaInf As String
Set ws = ActiveSheet
nomArch = Split(ws.Name, ".")(0)
wArch = ThisWorkbook.Path & "\" & ws.Range("B3").Text & ".dotx"
uf = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
For j = 5 To uf
If Not ws.Rows(j).Hidden Then 'visible rows only
Set wdDoc = objWord.Documents.Open(wArch)
nomFic = nomArch & "_" & ws.Cells(j, "A") & "_" & ws.Range("C3").Text
rutaInf = ThisWorkbook.Path & "\PrivacyPolicy PDFs\" & nomFic & ".pdf"
ReplaceAll wdDoc, "[Company_Name]", ws.Cells(j, "B")
ReplaceAll wdDoc, "[Vat_Number]", ws.Cells(j, "C")
ReplaceAll wdDoc, "[URL_Stay]", ws.Cells(j, "D")
ReplaceAll wdDoc, "[Update_Date]", ws.Cells(j, "E")
If Dir(rutaInf) <> "" Then Kill rutaInf
'Save file with the designated name
wdDoc.SaveAs Filename:=rutaInf, FileFormat:=wdFormatPDF
wdDoc.Close savechanges:=False
End If 'row not hidden
Next j
objWord.Quit 'close Word
End Sub
'Replace all instances of txtFind with txtReplace in doc
Sub ReplaceAll(doc As Word.Document, txtFind As String, txtReplace As String)
With doc.Range.Find
.Text = txtFind
.Replacement.Text = txtReplace
.Replacement.ClearFormatting
.Replacement.Font.Italic = False
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub

Return newly generated cell value in MsgBox

Whenever I run this code, it generates a sequential number.
I want to display the new sequential number in a MsgBox, but it prints the older sequential number.
Private Sub ToggleButton1_Click()
Dim reponse As VbMsgBoxResult
Dim REVISIONRNCAUTO As Workbook
Dim Sheet2 As Worksheet
Dim cell_value As String
Set REVISIONRNCAUTO = ActiveWorkbook
Set Sheet2 = REVISIONCRNAUTO.Worksheets(2)
cell_value = Sheet2.Cells(4, "A").Value & Sheet2.Cells(4, "B").Value
If CheckBox1.Value = True And CheckBox4.Value = True And CheckBox7.Value = True And CheckBox2.Value = False And CheckBox3.Value = False _
And CheckBox6.Value = False And CheckBox5.Value = False And CheckBox8.Value = False And CheckBox9.Value = False And CheckBox10.Value = False And CheckBox11.Value = False And CheckBox12.Value = False _
And CheckBox13.Value = False And CheckBox14.Value = False And CheckBox15.Value = False Then
Sheet2.Activate
reponse = MsgBox("Êtes-vous sûr de vouloir générer ce RNC?", vbYesNo + vbQuestion, "Enregistrement RNC")
If reponse = vbYes Then
Sheets("Sheet2").Range("B4").Select
ActiveCell.EntireRow.Insert shift:=xlDown
Sheets("Sheet2").Range("B4:E4").Select
Selection.Borders.Weight = xlThin
Sheets("Sheet2").Range("B4").Select
ActiveCell.Value = "=b5+1"
Sheets("Sheet2").Range("A4").Select
Selection.Borders.Weight = xlThin
ActiveCell.Value = "E"
Else
Exit Sub
End If
End If
MsgBox ("Le nouveau RNC enregistré est le : " & cell_value)
You aren't changing the value of cell_value after you set it.
They are not linked forever like an Excel formula. You have to set it again once you change the cells that it is based on.
Put the cell_value = line right before the Else in addition to where it currently is.

Excel VBA Macro - Replace a Reference word on Microsoft Word with a sentence above 255 from Excel

I want to replace a Reference word [Property Manager Notes] on Word with a paragraph which is greater than 255 words from Excel. There will be more references like these.
Could anyone help please.
Here is the picture to get an idea:
Here is the code I'm using
Dim objWord
Dim objDoc
Dim oCell As Integer
Sub Replacing_excel_word()
Sheets("Work").Select
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\Sai\Desktop\xyz.docx")
objWord.Visible = True
objWord.Activate
For oCell = 1 To 50
from_text = Sheets("Work").Range("A" & oCell).Value
to_text = Sheets("Work").Range("B" & oCell).Value
With objWord.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:=from_text, ReplaceWith:=to_text, Replace:=1
End With
End With
Next oCell
End Sub
I just solved this problem. At the end of your code you need to create a function:
Function Replacement255(wRng, field, content)
With wRng.Find
.text = field '>> enter the text to be searched and replaced
.MatchWholeWord = False
.MatchWildcards = False
If Len(content) > 255 Then
.Wrap = wdFindContinue
cnt = 0
Do
strFragment1 = Mid(content, cnt + 1, 230)
cnt = cnt + 230
If Len(strFragment1) > 0 Then strFragment1 = strFragment1 & "##########"
.Replacement.text = strFragment1
.Execute , , , , , , , , , , wdReplaceOne
.text = "##########"
Loop While Len(strFragment1) > 0
Else
.Replacement.text = text '>> enter column location of the text from excel
.Wrap = wdFindStop
.Execute Replace:=wdReplaceOne
End If
End With
End Function
And then, in your code, you need to use this function:
Replacement255 wRng, field, content.Value
where:
field: text to replace ex. "#Enter here#"
content: text to replace with ex. Sheet1.Cells(MyRow, "M")
I hope it helps you!

Resources