Save Excel Sheet text only to text file VBA - vba

I am trying to copy the values of one column in a sheet to a text file. The code I currently have causes runtime error 434.
Sheets("Output to fcf.1").Columns("A").SaveToText "P:\4_Calcs\02. Flag Mapping\test_.txt"
If I try and save the whole sheet
Sheets("Output to fcf.2").SaveToText "P:\Clear Project Drive\CLE10276 AWS SMP Model Assessmnts\4_Calcs\02. Flag Mapping\test2_.txt"
I get the entire sheet converted into text rather than just the text in the sheet. Is there a simple way to do this?
Thanks in advance!

Not sure which Excel version you have but I don't see a method for SaveToText.
But this procedure should work, or at least get you started...
Sub SaveColumn(sheetName As String, columnName As String, fileName As String)
Dim cell
Dim fso
Dim file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, True)
For Each cell In Sheets(sheetName).Columns(columnName).Cells
If cell.Value <> "" Then
file.WriteLine cell.Value
End If
Next
file.Close
Set file = Nothing
Set fso = Nothing
End Sub
To call it...
SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt"

This is designed to be used as a macro.
Step by step guide:
1) From excel, hit Alt+F11 on your keyboard.
2) From the menu bar, click Insert, then Module
3) Copy and paste the code provided below into the new module that opens.
NOTE: DocPath = "C:\docs\data.txt" should be wherever you want the output file saved, including the file's actual name. Remember, the folder you want the output file to be located in should ALREADY exist. This does not create the folder if it can't be found.
4) From the menu bar, click Tools, then References. Make sure both "Microsoft Office 14.0 Object Library" as well as "Microsoft Word 14.0 Object Library" are checked, and hit okay (See screenshot for details)
5) Save the document as an .xlsm file (This file type supports Macros)
6) Close the VBA editor. Back in Excel, on the ribbon click View and then Macros. Your new macro should be in the list as ExportToTXT
7) Select it and hit run.
Sub ExportToTXT()
Dim DocPath As String
Dim MsgBoxCompleted
Columns("A").Select
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = False
Selection.Copy
DocPath = "C:\docs\data.txt"
'Create and save txt file
AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
Application.CutCopyMode = False
AppWord.Quit (wdDoNotSaveChanges)
Set AppWord = Nothing
MsgBoxCompleted = MsgBox("Process complete.", vbOKOnly, "Process complete")
End Sub
Good luck, and if you have any questions, don't hesitate to ask.
NOTE: These directions might seem overly simplified for your skill level, but I wrote the answer like this to potentially help others in the future.
EDIT
Change
DocPath = "C:\docs\data.txt"
to
DocPath = "C:\docs\data.fcf"
And change
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
to
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath
The output file will be .fcf format. Whether or not it will open properly is something I'm not sure of. You'd have to test in the program you're using.

Related

Issues with detecting open file

I have literally copied and pasted and tested every bit of code from may BBs and the same thing happens with all of them. they all either tell me that that the file is open if it's open or closed or they tell me that the file is closed when it is open or closed. The code never gets it correct. Here is the last thing I tried and it was telling me it was not open when it was and when it wasn't
Can someone tell me if this is due to the file being located on the network
Sub Is_WorkBook_Open()
Dim wBook As Workbook
On Error Resume Next
Set wBook = Workbooks("X:\Audit Tracking\Team_Larry\DailyReports\Larry_Blank.xlsm")
'Not open
If wBook Is Nothing Then
MsgBox "Larry's Workbook is not open, Proceed to posting", vbCritical
Set wBook = Nothing
On Error GoTo 0
'It is open
Else
MsgBox "Yes it is open, Notify Supervisor to close file", vbInformation
Set wBook = Nothing
On Error GoTo 0
End If
End Sub
it was telling me it was not open when it was and when it wasn't
The Application.Workbooks collection contains all the workbooks opened in this instance of Excel.Application; if the workbook is opened by someone else on another machine, it's not in the collection and you can't use that method to know this.
If you're using the latest & greatest Excel 2016 on Office 365, see how you can dismiss that concern altogether using co-authoring features.
Otherwise, you can try sharing the workbook and then Excel can tell you exactly who has it opened, but then shared workbooks has a number of issues, including but not limited to, the inability to edit VBA code.
Using a hard-coded path is a good way to get false negatives, too. Open the file, verify its actual FullName and use that.
Dim i As Long
For i = 1 To Application.Workbooks.Count
Debug.Print Application.Workbooks(i).FullName
Next
If the file's location doesn't really matter, only its file name, you can iterate the opened files and see if one has a matching file name:
Dim i As Long
For i = 1 To Application.Workbooks.Count
If Application.Workbooks(i).Name = "Larry_Blank.xlsm" Then
MsgBox "File is opened."
Exit For
End If
Next
When you open an Excel workbook a hidden temporary copy of the workbook will be created. This is presumably used to recovery crashed files. Notice that the temporary workbook's name and path is the same as the actual workbook but has ~$ prefixed to the filename. Since the file path remains the same, we can assume that the ↓`isWorkbookOpen()↓ will work even with mapped and shared folders.
Function isWorkbookOpen(Path As String) As Boolean
Dim values() As String
values = Split(Path, "\")
values(UBound(values)) = "~$" & values(UBound(values))
Path = Join(values, "\")
isWorkbookOpen = Len(Dir(Path, vbHidden)) > 0
End Function
I believe your code will test if you have it open, on the computer your running the code from.
This code will open the workbook, if it opens in a read only state then someone else has it open. Note: If you open it on your computer, and then run this code on the same computer it will report that it's not in a read only state.
Sub Test()
Dim oWB As Workbook
Set oWB = Application.Workbooks.Open("C:\Temp\test.xlsx")
If oWB.ReadOnly Then
MsgBox "Open"
Else
MsgBox "Closed"
End If
oWB.Close
End Sub

How to Open Embedded Object in Excel with Caption in Vba?

Try to open embedded object in excel file with caption,able to open file with name: can any one help how to open with caption or dynamically
Worksheets(SheetName).Activate
Set o = Worksheets(SheetName).OLEObjects("object 3")
o.Verb xlVerbOpen
MsgBox "Attachmene open"
Note: object will add continuously in excel file, how to find object dynamically to open with caption?
The embedded object in Excel is a Shape. Add two embeded workbooks in your ActiveSheet and try this code:
Public Sub TestMe()
Dim obj As Object
For Each obj In ActiveSheet.Shapes
Debug.Print obj.Application.Caption
Next obj
End Sub
Then try to change the code, with a simple condition, opening the obj, if the caption is the expected one:
If obj.Application.Caption = "someCaption" Then OpenTheWorkbook(obj)
At the end write some check to make sure that it skips some possible errors.
I open an embedded WORD document through Excel using the following verb command.
Set o = .OLEObjects("Object 1")
o.Verb xlVerbOpen
"Object 1" is the default name of the embedded object so that would be changed as needed.

To access an Excel file from a Sharepoint Folder

I am using the below code, to open the Excel file from SharePoint.
I am Little confused how, I should code, for the accessing the file from an Folder in SharePoint.
The Excel file, i Need is stored in ; SharePoint>> Document >> Test >> Data >>July
and the link to my SharePoint is like this, https://forum/content/008200/default.aspx?RootFolder=%2Fcontent%2F00008200%20Documents%2DTest%2F0001%20%29&FolderCTID=0x01200083BC38D90EC5674491B520CC48282737&View={00112127-0FE6-44A4-A5FB-86BC6C4E835B}&InitialTabId=Ribbon%2EDocument&VisibilityContext=WSSTabPersistence
Could someone help me, How i should code, to acess an Excel file from a Folder in SharePoint.
I have attached a Piece of code, which i reffered it from the Forum. and would be helpful, if you could comment the lines, if you can suggest me a code.
Sub Share()
Dim SWB As Workbook
Dim WB As Variant
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "https://forum/Content/008200/default.aspx" & "\"
.AllowMultiSelect = False
.show
For Each WB In .SelectedItems
Set SWB = Workbooks.Open(WB)
Next
End With
If SWB Is Nothing Then Exit Sub
End Sub
i don't know , how can you with vb but i assume your file in Document Library if it is you can use this code to get document.
SPFile myExcelFile = SPContext.Current.Web.GetFile("/Documents/Test/Data/July/excelFile.xslx");
Stream excelFileStream = myExcelFile.OpenBinaryStream();

Setting Document Properties while saving individual sheets

I'm not familiar with VBA at all so this has me stumped, hoping someone can help.
I have a template on a sharepoint server that is working correctly. In order to save the xlsm file with the server document properties, I have a command button which runs the following:
Sub UpdateDB()
For Each Prop In ThisWorkbook.ContentTypeProperties
If Prop.Name = "Name" Then
Prop.Value = Range("B8").Value
End If
Next Prop
Filename = Range("B59").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=52
End Sub
This is working well.
I now have another template which I want to do a similar thing but there are some complications:
I have several worksheets which I would like saved as individual files containing only the said worksheet.
The document properties for each file should different, based on a cell in each worksheet.
Now I have managed to setup point 1 and it's working OK using the following code:
Sub NewSub()
Worksheets("EMP1").Activate
Filename = Range("B1").Value
Dim wb as Workbook
Application.ActiveSheet.Copy
Set wb = ActiveWorkbook
With wb
.SaveAs Filename:=Filename, FileFormat:=52
End With
End Sub
This is working well but if I try adding in code to set the Document Properties, it doesn't work, it won't carry them through to the new file. I have tried adding the code which sets the document properties after line 2 and I have tried adding it also after line 7; it doesn't throw an error but it doesn't set any document properties either. Any help on this would be much appreciated. Thanks.

Word vba document.readonly status incorrectly returns false

I have an excel project that checks word documents for a changed modify date and, if changed, it opens that document and imports the text from the word form fields into excel.
The routine in excel that opens and imports the word documents is as follows:
Sub CopyFromWord(pFile as String,aFile as string)
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
Else 'word is already running
End If
On Error Goto 0
Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True)
wdApp.Visible = False
For Each c In wdDoc.bookmarks
'removed code that copies values from word doc fields to excel sheet
Next c
wdApp.Activedocument.Close SaveChanges:=False
End Sub
The word documents all started out as copies of the same file. There are a few thousand copies of the file, but each located in their own folder with a unique name.
The user finds the folder they need and opens the word document within it. It bring up a userform and then populates formfields in the document with the input to the userform. A command button then saves and exits the form.
Because the welcome message/userform loads automatically upon the document opening, I added the following code into the open event for the document:
Sub Document_Open()
If ThisDocument.ReadOnly = True then Exit Sub
msgbox "Welcome " & Environ$("Username") & ". Click OK to begin."
Userform1.show
End sub
This ensures when the excel project loops through all the files, if it finds one has changed, it needs to open the file (read only) so it can import the data without being interrupted with a userform / welcome message, close it, and carry on searching looping all files checking for changed modify-dates.
It should run constantly, however, about 20% of the time, a document will be opened read only by the excel code, but the welcome messagebox in the word document will show, indicating thisdocument.readonly incorrectly returned false.
If I debug the word document in this scenario, and do
? thisdocument.readonly
I get a "false" result. However, even the title bar of the word document ends with " (Read-Only)" so it has clearly been opened read-only, thus readonly should return True.
It is not specific to any documents, if I try to repeat opening them it seems to work the next time round (in that it correctly registers a read-only and exits the sub before the messagebox code). I cant find any kind of pattern and can't find any info online, I've been searching this for weeks!
May not be considered the answer, but following Tim William's suggestion, I managed to put together this which completely solves my problem. I struggled at first because I was trying to set the property too early. Complete code is as follows:
Sub CopyFromWord(pFile as String)
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
Else 'word is already running
End If
On Error Goto 0
'save current setting
secAutomation = wrdApp.Application.AutomationSecurity
'set Word to disable macros when a document is opened via vb:
wrdApp.Application.AutomationSecurity = msoAutomationSecurityForceDisable
'(without using wrdApp prefix it would only apply to the code's App i.e. Excel)
Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True)
wdApp.Visible = False
For Each c In wdDoc.bookmarks
'removed code that copies values from word doc fields to excel sheet
Next c
'restore original setting before closing
wrdApp.Application.AutomationSecurity = secAutomation
wdApp.Activedocument.Close SaveChanges:=False
End Sub
Many thanks to Tim Williams for the link, and the guy who provided the code within the content of that link. This was such a help and is most appreciated.