Read a Text File with VBA in Excel, and Write the Text to a Spreadsheet
2014-11-30 20:14
806 查看
VBA can read a text file and then write it to your spreadsheet. Here's an example of a VBA program that shows how to do it.
http://exceluser.com/excel_help/questions/vba_textcols.htm"I need to write a text file into one row of my Excel spreadsheet, cell by cell, 20 characters at a time. It's urgent. Can you help?" -- Kumar
Kumar,
It's sort of a strange request. But it sounds like fun. And it demonstrates how we can read text files into Excel using VBA.
By the way, the following code illustrates the various points I discussed in Corporate VBA Standards For Excel Users Who Program.
To begin, create a new workbook with two sheets. Name one sheet Control and the other Target.
In the Control worksheet, enter the text shown in column A:
Assign the range names shown in column A to cells in column B. To do so, select the range A4:B9. Choose Insert, Name, Create. In the Create Names dialog, ensure that only Left Column is checked. Then choose OK.
Enter the path and name for your text file. (I used File Explorer to navigate to its directory and then copied the path text from the Address bar.) Enter the other information shown.
Leave the Target sheet blank.
Press Alt+F11 to bring up the Visual Basic editor. To create a new module, right-click your workbook's name in the editor's project window and choose Insert, Module.
Then copy and paste the following code to your module.
''Require that all variables be declared Option Explicit ''====================================================== '' Program: ParseText '' Desc: Reads a text file into a variable then '' writes it into a row, n chars at a time '' Called by: user '' Call: '' Arguments: '' Comments: Written quickly. No error-checking. '' Changes---------------------------------------------- '' Date Programmer Change '' 6/14/06 Charley Kyd Written ''====================================================== Sub ParseText() Dim sText As String, sFile As String ''Get the full path to the source file With ThisWorkbook sFile = .Names("SourcePath").RefersToRange If Left(sFile, 1) <> "\" Then sFile = sFile & "\" sFile = sFile & .Names("SourceFile").RefersToRange End With ''Get the full text string from the text file sText = GetText(sFile) ''Remove all nonprintable characters from the text ''Comment out if the characters are wanted sText = Excel.WorksheetFunction.Clean(sText) ''Write to the workbook WriteToSheet sText End Sub ''====================================================== '' Program: GetText '' Desc: Read a text file into a string and then '' return the string '' Called by: ParseText '' Call: GetText(sFile) '' Arguments: sFile--The full path to the text file '' Comments: '' Changes---------------------------------------------- '' Date Programmer Change '' 6/14/06 Charley Kyd Written ''====================================================== Function GetText(sFile As String) As String Dim nSourceFile As Integer, sText As String ''Close any open text files Close ''Get the number of the next free text file nSourceFile = FreeFile ''Write the entire file to sText Open sFile For Input As #nSourceFile sText = Input$(LOF(1), 1) Close GetText = sText End Function ''====================================================== '' Program: WriteToSheet '' Desc: Writes a text string to one row of a '' worksheet, n characters per column '' Called by: ParseText '' Call: WriteToSheet sText '' Arguments: sText--String with text from text file '' Comments: This routine will throw an error if the '' text is too long to fit within 256 columns '' Changes---------------------------------------------- '' Date Programmer Change '' 6/14/06 Charley Kyd Written ''====================================================== Sub WriteToSheet(sText As String) Dim sTgtSheet As String, nTgtRow As Integer Dim nColCount As Integer, sChunk As String Dim nIncrement As Integer, rngRef As Range ''Get the controlling variables With ThisWorkbook sTgtSheet = .Names("TargetSheet").RefersToRange nTgtRow = .Names("TargetRow").RefersToRange nIncrement = .Names("Increment").RefersToRange Set rngRef = Worksheets(sTgtSheet).Cells(nTgtRow, 1) End With ''Erase any previous entries rngRef.EntireRow.ClearContents ''Initialize the column counter nColCount = 0 ''Loop thru the string, grabbing text of specified ''length, writing the text to the spreadsheet Do ''Increment the column count nColCount = nColCount + 1 ''Grab the current chunk of text sChunk = Mid$(sText, 1 + (nColCount - 1) * _ nIncrement, nIncrement) ''Write it to the spreadsheet rngRef.Cells(1, nColCount) = sChunk ''Stop after writing a partial chunk Loop Until Len(sChunk) < nIncrement End Sub |
macro easily. To do so, first activate your Control sheet.
Right-click any toolbar. Click on Forms if its not already
checked.
Click on the Button icon in the Forms toolbar. Doing so turns
your pointer into a cross. Use the cross to draw the outline of
a button on your worksheet.
When you release your left mouse button, Excel draws the
button and launches the Assign Macro dialog. Choose the
ParseText macro, then choose OK. Select the text "Button 1" in
the button and then type any text you want, like "Parse Text".
Then click on any cell to deselect the button.
Now, when you click on the button, Excel should run your
macro and write your text to your Target worksheet.
相关文章推荐
- CSpreadSheet - A Class to Read and Write to Excel and Text Delimited Spreadsheet
- CSpreadSheet - A Class to Read and Write to Excel and Text Delimited Spreadsheet
- How to mount partition with ntfs file system and read write access
- Use the SQL Server CLR to Read and Write Text Files
- Read and write excel file with format by pandas and xlwt libraries of python
- How to mount partition with ntfs file system and read write access
- Simple VBScript program to extract data from all worksheets in an Excel spreadsheet
- How To Read and Write XML Documents with GDataXML
- How to get the password text in a text with password property from another process using C++ - 用C++如何从不同进程获取密码框文本
- read and write excel file as a table
- SharePoint Project Deployment Fails With Error "Failed to extract the cab file in the solution"
- How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
- how to use a SQLite database in a standalone program with an HTML interface and VBScript as the programming language
- [Drupal] How to add the js file and js code block in Drupal
- Read and Write compressed data to a binary file using ASP.NET
- If you whant to download SIS, JAR and JAD file from WAP you have to upload file (in the same catalog) with this: [小糊涂的灵感]
- How to change the name in open with list / File association.
- BI Java 补丁错误处理 :Cannot login to the SAP J2EE Engine using user and password as provided in the Filesystem Secure Store. Enter va
- prjGetWriteINIFile - How to Read-Write INI file using VB & API - 读取/写入INI文件 - VB6 + API - SourceCode - HackerJLY
- Create, Read, Write, Copy, Move and Delete a Text File using C#