Excel VBA_文本文件和文件夹操作实例集锦

合集下载

VBA中的文件夹批量操作技巧与示例

VBA中的文件夹批量操作技巧与示例

VBA中的文件夹批量操作技巧与示例在进行VBA编程时,经常需要对文件夹进行批量操作,例如批量创建文件夹、批量复制或移动文件夹、批量删除文件夹等。

本文将介绍如何使用VBA实现这些文件夹的批量操作,并给出相应的示例代码。

1. 批量创建文件夹在VBA中,可以使用FileSystemObject对象的CreateFolder方法来创建文件夹。

首先,需要引用Microsoft Scripting Runtime库,然后使用下面的代码示例来批量创建文件夹:```vbaSub CreateFolders()Dim fso As ObjectDim folderPath As StringDim i As IntegerSet fso = CreateObject("Scripting.FileSystemObject")folderPath = "C:\Folder\" '指定要创建的文件夹路径For i = 1 To 10 '指定要创建的文件夹数量fso.CreateFolder folderPath & "Folder" & iNext iSet fso = NothingEnd Sub上述代码使用了循环结构和字符串拼接来批量创建指定数量的文件夹。

你只需修改folderPath变量的值为你想要创建文件夹的路径,并修改循环的起始值和终止值即可。

2. 批量复制或移动文件夹在VBA中,可以使用FileSystemObject对象的CopyFolder和MoveFolder方法来实现文件夹的复制和移动操作。

下面是示例代码:```vbaSub CopyOrMoveFolders()Dim fso As ObjectDim sourceFolderPath As StringDim destinationFolderPath As StringSet fso = CreateObject("Scripting.FileSystemObject")sourceFolderPath = "C:\Folder1\" '指定要复制或移动的文件夹路径destinationFolderPath = "C:\Folder2\" '指定目标文件夹路径'复制文件夹fso.CopyFolder sourceFolderPath, destinationFolderPath'或者移动文件夹'fso.MoveFolder sourceFolderPath, destinationFolderPathSet fso = NothingEnd Sub在上述示例代码中,你需要将sourceFolderPath和destinationFolderPath变量的值修改为你要复制或移动的文件夹路径和目标文件夹路径。

VBA批量处理文本文件的实例教程

VBA批量处理文本文件的实例教程

VBA批量处理文本文件的实例教程VBA(Visual Basic for Applications)是微软公司开发的一种基于Visual Basic的宏编程语言,广泛应用于Microsoft Office软件中。

在Excel中,我们可以利用VBA编写程序,实现自动化操作,并且可以处理各种类型的文件,包括文本文件。

本文将介绍如何使用VBA批量处理文本文件的实例教程。

VBA是Excel的内置宏语言,可以通过点击"开发工具",并启用"开发工具"选项卡来访问。

在VBA编辑器中,可以编写和编辑VBA代码。

首先我们将了解如何打开文本文件、读取、写入和保存文本文件。

步骤一:打开文本文件首先,我们需要通过VBA代码打开一个或多个文本文件。

可以使用"Open"语句来打开文本文件。

下面的代码演示了如何通过VBA打开一个文本文件:```vbaSub OpenTextFile()Dim FilePath As StringDim TextFile As IntegerFilePath = "C:\path\to\file.txt" '替换为你的文件路径TextFile = FreeFileOpen FilePath For Input As TextFile'在这里进行文件操作Close TextFileEnd Sub```在上述代码中,首先定义了一个变量`FilePath`,用于存储文本文件的路径。

然后使用`FreeFile`函数定义了一个整数变量`TextFile`,它将被用来标识文本文件。

接下来使用`Open`语句打开文本文件,并将其与`TextFile`进行关联。

在这里你可以替换为你的文件路径。

最后使用`Close`语句关闭文件。

步骤二:读取文本文件打开文本文件后,我们可以通过VBA代码读取文本文件的内容。

可以使用`Input`和`Line Input`语句来逐行读取文本文件的内容。

VBA中的文件路径与文件夹操作

VBA中的文件路径与文件夹操作

VBA中的文件路径与文件夹操作在进行VBA编程时,经常需要处理文件的操作,包括获取文件路径、创建文件夹、复制和移动文件等。

本文将介绍VBA中的文件路径与文件夹操作的相关知识,并提供一些实用的代码示例。

1. 获取文件路径要获取文件的路径,可以使用VBA提供的Dir和FileDialog函数。

Dir函数可以用于检索指定路径下的文件名列表,而FileDialog函数则可以打开文件对话框,让用户选择文件并返回其路径。

以下是使用Dir函数获取文件路径的示例代码:```Sub GetFilePath_Dir()Dim filePath As StringfilePath = Dir("C:\Users\Username\Documents\example.txt")If filePath <> "" ThenDebug.Print "文件路径:" & filePathElseDebug.Print "未找到文件"End IfEnd Sub```以下是使用FileDialog函数获取文件路径的示例代码:```Sub GetFilePath_FileDialog()Dim filePath As StringDim fileDialog As ObjectSet fileDialog = Application.FileDialog(msoFileDialogFilePicker) With fileDialog.AllowMultiSelect = False.Title = "选择文件"If .Show = -1 ThenfilePath = .SelectedItems(1)Debug.Print "文件路径:" & filePathElseDebug.Print "未选择文件"End IfEnd WithSet fileDialog = NothingEnd Sub```2. 创建文件夹在VBA中,要创建一个文件夹,可以使用FileSystemObject对象的CreateFolder方法。

VBA文件及文件夹操作

VBA文件及文件夹操作

Excel:VBA 文件及文件夹操作2011年06月12日星期日 09:08VBA文件及文件夹操作1.VBA操作文件及文件夹on error resume next下测试A,在D:\下新建文件夹,命名为folder方法1:MkDir "D:\folder"方法2:Set abc = CreateObject("Scripting.FileSystemObject")abc.CreateFolder ("D:\folder")B,新建2个文件命名为a.xls和b.xlsWorkbooks.AddActiveWorkbook.SaveAs Filename:="D:\folder\a.xls"ActiveWorkbook.SaveAs Filename:="D:\folder\b.xls"C,创建新文件夹folder1并把a.xls复制到新文件夹重新命名为c.xlsMkDir "D:\folder1"FileCopy "D:\folder\a.xls", "D:\folder1\c.xls"D,复制folder中所有文件到folder1Set qqq = CreateObject("Scripting.FileSystemObject")qqq.CopyFolder "D:\folder", "D:\folder1"D,重命名a.xls为d.xlsname "d:\folder1\a.xls" as "d:\folder1\d.xls"E,判断文件及文件夹是否存在Set yyy = CreateObject("Scripting.FileSystemObject")If yyy.FolderExists("D:\folder1) = True Then ...If yyy.FileExists("D:\folder1\d.xls) = True Then ...F,打开folder1中所有文件Set rrr = CreateObject("Scripting.FileSystemObject")Set r = rrr.GetFolder("d:\folder1")For Each i In r.FilesWorkbooks.Open Filename:=("d:\folder1\" + + "")NextG,删除文件c.xlskill "d:\folder1\c.xls"H,删除文件夹folderSet aaa = CreateObject("Scripting.FileSystemObject")aaa.DeleteFolder "d:\folder"2.excel vba一次性获取文件夹下的所有文件名的方法小生今天上网下载了一个财务常用报表的文件包,里面有几百个excel工作表,要是手工一个一个的获得文件名的话,那我可是要忙十天半月哦。

VBA文件及文件夹操作

VBA文件及文件夹操作

VBA文件及文件夹操作VBA(Visual Basic for Applications)是一种用于自动化任务和数据处理的编程语言,可以用于操作各种文件和文件夹。

在本文中,我将介绍一些常见的VBA文件和文件夹操作技巧。

1.创建文件夹:你可以使用VBA在指定路径下创建一个新的文件夹。

下面是一个创建文件夹的示例代码:```Sub CreateFolderDim FolderPath As StringFolderPath = "C:\NewFolder"MkDir FolderPathEnd Sub```该代码将在C盘根目录下创建一个名为“NewFolder”的文件夹。

2.删除文件夹:你可以使用VBA删除指定路径下的文件夹。

以下是一个删除文件夹的示例代码:```Sub DeleteFolderDim FolderPath As StringFolderPath = "C:\FolderPath"RmDir FolderPathEnd Sub```该代码将删除C盘根目录下的“FolderPath”文件夹。

3.复制文件:你可以使用VBA复制文件到另一个位置。

以下是一个复制文件的示例代码:```Sub CopyFileDim SourcePath As String, DestinationPath As StringSourcePath = "C:\SourcePath\file.txt"DestinationPath = "C:\DestinationPath\file.txt"FileCopy SourcePath, DestinationPathEnd Sub```该代码将“C:\SourcePath”目录下的“file.txt”文件复制到“C:\DestinationPath”目录下。

4.删除文件:你可以使用VBA删除指定路径下的文件。

VBA中的文件操作详解与实例

VBA中的文件操作详解与实例

VBA中的文件操作详解与实例VBA(Visual Basic for Applications)是一种用于自动化任务的编程语言,常用于Microsoft Office套件中的各种应用程序,如Excel、Word和PowerPoint等。

文件操作是VBA编程中的常见需求,包括创建、打开、保存和关闭文件等。

本文将详细介绍VBA中文件操作的各种方法,并提供实例代码以便读者更好地理解和应用这些技巧。

1. 创建新文件要在VBA中创建新文件,可以使用CreateObject函数来实现。

例如,要创建一个新的Excel文件,可以使用以下代码:```Dim objExcel As ObjectSet objExcel = CreateObject("Excel.Application")objExcel.Visible = True '显示新创建的Excel应用程序objExcel.Workbooks.Add '创建新的工作簿```在这个示例中,我们使用CreateObject函数创建了一个Excel应用程序对象,并设置其Visible属性为True,以便在屏幕上显示该应用程序。

然后,通过调用Workbooks对象的Add方法,我们创建了一个新的工作簿。

2. 打开现有文件在VBA中,要打开现有的文件,可以使用Workbooks.Open方法。

以下是一个打开Excel文件的例子:```Dim objExcel As ObjectSet objExcel = CreateObject("Excel.Application")objExcel.Visible = True '显示Excel应用程序objExcel.Workbooks.Open "C:\path\to\your\file.xlsx" '打开指定的Excel文件```在这个示例中,我们首先创建了一个Excel应用程序对象。

VBA文件和文件夹操作指南

VBA文件和文件夹操作指南

VBA文件和文件夹操作指南在日常的办公工作中,我们经常需要使用VBA(Visual Basic for Applications)来进行文件和文件夹的操作。

VBA 是微软为Office套件开发的一种宏语言,它能够实现自动化任务,提高工作效率。

本文将为您介绍如何使用VBA 进行文件和文件夹的操作。

一、文件操作指南1. 打开和关闭文件使用VBA可以轻松地打开和关闭文件。

下面是一个示例代码:```vbaSub OpenAndCloseFile()Dim FilePath As StringFilePath = "C:\folder\file.txt" ' 文件的完整路径' 打开文件Workbooks.Open FilePath' 签出文件以编辑ActiveWorkbook.CheckOut' 对文件进行一些操作' ...' 保存并关闭文件ActiveWorkbook.CheckIn TrueActiveWorkbook.Close SaveChanges:=FalseEnd Sub```2. 保存文件使用VBA可以方便地保存文件。

下面是一个示例代码:```vbaSub SaveFile()Dim FilePath As StringFilePath = "C:\folder\file.txt" ' 文件的完整路径' 打开文件Workbooks.Open FilePath' 对文件进行一些操作' ...' 保存文件ActiveWorkbook.Save' 关闭文件ActiveWorkbook.Close SaveChanges:=FalseEnd Sub```3. 新建文件使用VBA可以通过指定模板来新建文件。

下面是一个示例代码:```vbaSub CreateNewFile()Dim NewFilePath As StringNewFilePath = "C:\folder\newfile.xlsx" ' 新建文件的完整路径' 新建一个工作簿Workbooks.Add' 对新建文件进行一些操作' ...' 保存文件ActiveWorkbook.SaveAs NewFilePath' 关闭文件ActiveWorkbook.Close SaveChanges:=FalseEnd Sub```二、文件夹操作指南1. 创建文件夹使用VBA可以轻松地创建新的文件夹。

VBA处理文本文件方法与实例应用

VBA处理文本文件方法与实例应用

VBA处理文本文件方法与实例应用在VBA编程中,处理文本文件是非常常见的任务。

无论是读取文件内容、写入文件还是对文件进行修改,都需要使用适当的方法和技巧。

本文将介绍VBA处理文本文件的常用方法,并通过实例应用来演示具体的操作步骤。

1. 打开文本文件要处理文本文件,首先需要打开文件并将其读取到内存中。

VBA提供了Open语句用于打开文件。

下面是一个打开文本文件的示例:```Dim filePath As StringDim fileNum As IntegerfilePath = "C:\path\to\file.txt"fileNum = FreeFileOpen filePath For Input As fileNum```在上面的代码中,我们定义了一个文件路径(filePath)和一个文件号(fileNum)。

接下来,使用Open语句将文件以输入方式打开。

2. 读取文件内容一旦文本文件被打开,就可以使用Input函数读取文件的内容。

Input函数可以逐行读取文件,并将每一行的内容作为字符串返回。

下面是一个读取文件内容的示例:```Dim line As StringDo Until EOF(fileNum)Line Input #fileNum, line' 对读取到的每一行进行处理' ...LoopClose fileNum```在上面的代码中,我们使用了一个循环结构,通过Line Input语句逐行读取文件内容,并将每一行的内容保存在变量line中。

在循环体中,可以对读取到的每一行进行进一步的处理。

3. 写入文件除了读取文件,VBA还可以通过Print语句将内容写入一个新的文本文件。

下面是一个写入文件的示例:```Dim filePath As StringDim fileNum As IntegerfilePath = "C:\path\to\output.txt"fileNum = FreeFileOpen filePath For Output As fileNumPrint #fileNum, "Hello, World!"Print #fileNum, "This is a sample text."Close fileNum```在上面的代码中,我们将文件以输出方式打开,并使用Print 语句将文本写入文件。

ExcelVBA中文件夹操作代码小集

ExcelVBA中文件夹操作代码小集

ExcelVBA中文件夹操作代码小集'1 判断文件夹是否存在'dir函数的第二个参数是vbdirectory时可以返回路径下的指定文件和文件夹,如果结果为'',则表示不存在。

Sub w1()If Dir(ThisWorkbook.path & '\2011年报表2', vbDirectory) = '' ThenMsgBox '不存在'ElseMsgBox '存在'End IfEnd Sub'2 新建文件夹'Mikdir语句可以创建一个文件夹Sub w2()MkDir ThisWorkbook.path & '\Test'End Sub'3 删除文件夹'RmDir语句可以删除一个文件夹,如果想要使用RmDir 来删除一个含有文件的目录或文件夹,则会发生错误。

'在试图删除目录或文件夹之前,先使用Kill 语句来删除所有文件。

Sub w3()RmDir ThisWorkbook.path & '\test'End Sub'4 文件夹重命名Sub w4()Name ThisWorkbook.path & '\test' As ThisWorkbook.path & '\test2'End Sub'5 文件夹移动'同样使用name方法,可以达到移动的效果,而且连文件夹的文件一起移动Sub w5()Name ThisWorkbook.path & '\test2' As ThisWorkbook.path & '\2011年报表\test100'End Sub'6 文件夹复制Sub CopyFile_fso()Dim fso As ObjectSet fso = CreateObject('Scripting.FileSystemObject')fso.CopyFolder ThisWorkbook.path & '\测试新建文件夹', ThisWorkbook.path & '\2011年报表\'Set fso = NothingEnd Sub'7 打开文件夹'使用shell函数桌面管理程序打开文件夹Sub w7()Shell 'explorer.exe ' & ThisWorkbook.path & '\2011年报表', 1 End Sub【摘自兰色VBA80集视频教程第48集】。

VBA中的文件夹操作方法与实例

VBA中的文件夹操作方法与实例

VBA中的文件夹操作方法与实例在VBA编程中,文件夹操作是一个常见的需求。

它可以帮助我们管理文件夹的创建、重命名、删除等操作,从而实现更高效、自动化的数据处理和文件管理。

本文将介绍VBA中常用的文件夹操作方法,并提供一些实际应用实例。

一、创建文件夹如果我们需要在VBA中创建一个新的文件夹,可以使用FileSystemObject对象的CreateFolder方法。

下面是一个创建文件夹的示例代码:```vbaSub CreateFolderExample()Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim folderPath As StringfolderPath = "C:\NewFolder"If Not fso.FolderExists(folderPath) Thenfso.CreateFolder folderPathMsgBox "文件夹创建成功!"ElseMsgBox "文件夹已存在!"End IfSet fso = NothingEnd Sub```在上述示例代码中,首先我们创建了一个FileSystemObject对象,并将其分配给变量fso。

然后定义了一个文件夹路径,这里我们创建了一个名为"NewFolder"的文件夹。

接下来,使用FolderExists方法判断文件夹是否已经存在,如果不存在,则使用CreateFolder方法创建文件夹,并通过消息框提示创建成功。

如果文件夹已经存在,则通过消息框提示文件夹已存在。

二、重命名文件夹在VBA中重命名文件夹同样使用FileSystemObject对象的MoveFolder方法。

下面是一个重命名文件夹的示例代码:```vbaSub RenameFolderExample()Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim oldFolderPath As StringDim newFolderPath As StringoldFolderPath = "C:\OldFolder"newFolderPath = "C:\NewFolder"If fso.FolderExists(oldFolderPath) Thenfso.MoveFolder oldFolderPath, newFolderPathMsgBox "文件夹重命名成功!"ElseMsgBox "文件夹不存在!"End IfSet fso = NothingEnd Sub```在上述示例代码中,我们首先创建了一个FileSystemObject对象,并将其分配给变量fso。

VBA中批量处理文件和文件夹的实用技巧与方法

VBA中批量处理文件和文件夹的实用技巧与方法

VBA中批量处理文件和文件夹的实用技巧与方法在日常工作中,我们经常需要处理大量的文件和文件夹。

手动处理这些文件非常耗时且容易出错,因此学习如何利用VBA编程语言来批量处理文件和文件夹是非常实用的技巧。

本文将介绍几种使用VBA进行文件和文件夹批量处理的方法,帮助您提高工作效率和减少繁琐的重复操作。

一、批量处理文件1. 批量打开文件有时我们需要同时打开多个文件进行处理,手动一个个打开文件既浪费时间又容易出错。

使用VBA可以批量打开文件,简化操作步骤。

以下是示例代码:```vbaSub BatchOpenFiles()Dim myFolder As String, myFile As StringmyFolder = "C:\ExampleFolder\" '指定文件夹路径myFile = Dir(myFolder & "\*.xlsx") '过滤器为.xlsx文件Do While myFile <> ""Workbooks.Open (myFolder & "\" & myFile)myFile = DirLoopEnd Sub```在上述示例中,我们通过指定文件夹路径和过滤器,循环遍历文件夹下的所有符合条件的文件,并逐个打开。

2. 批量保存文件保存文件是常见而又繁琐的操作,使用VBA可以批量保存文件,节省时间和精力。

以下是示例代码:```vbaSub BatchSaveFiles()Dim myFolder As String, myFile As StringmyFolder = "C:\ExampleFolder\" '指定文件夹路径myFile = Dir(myFolder & "\*.xlsx") '过滤器为.xlsx文件Do While myFile <> ""Workbooks.Open (myFolder & "\" & myFile)ActiveWorkbook.SaveActiveWorkbook.ClosemyFile = DirLoopEnd Sub```在上述示例中,我们打开并保存了文件夹下的所有.xlsx文件,并逐个关闭。

(完整word版)ExcelVBA编程实例(150例)

(完整word版)ExcelVBA编程实例(150例)

ExcelVBA编程实例(150例)主要内容和特点《ExcelVBA编程入门范例》主要是以一些基础而简短的VBA实例来对ExcelV BA中的常用对象及其属性和方法进行讲解,包括应用程序对象、窗口、工作簿、工作表、单元格和单元格区域、图表、数据透视表、形状、控件、菜单和工具栏、帮助助手、格式化操作、文件操作、以及常用方法和函数及技巧等方面的应用示例。

这些例子都比较基础,很容易理解,因而,很容易调试并得以实现,让您通过具体的实例来熟悉ExcelVBA编程。

■ 分16章共14个专题,以具体实例来对大多数常用的ExcelVBA对象进行讲解;■ 一般而言,每个实例都很简短,用来说明使用VBA实现Excel某一功能的操作;■ 各章内容主要是实例,即VBA代码,配以简短的说明,有些例子可能配以必要的图片,以便于理解;■ 您可以对这些实例进行扩充或组合,以实现您想要的功能或更复杂的操作。

VBE编辑器及VBA代码输入和调试的基本知识在学习这些实例的过程中,最好自已动手将它们输入到VBE编辑器中调试运行,来查看它们的结果。

当然,您可以偷赖,将它们复制/粘贴到代码编辑窗口后,进行调试运行。

下面,对VBE编辑器界面进行介绍,并对VBA代码输入和调试的基本知识进行简单的讲解。

激活VBE编辑器一般可以使用以下三种方式来打开VBE编辑器:■ 使用工作表菜单“工具——宏——Visual Basic编辑器”命令,如图00-01所示;■ 在Visual Basic工具栏上,按“Visual Basic编辑器”按钮,如图00-02所示;■ 按Alt+F11组合键。

图00-01:选择菜单“工具——宏——Visual Basic编辑器”命令来打开VBE编辑器图00-02:选择Visual Basic工具栏上的“Visual Basic编辑器”命令按钮来打开VBE编辑器此外,您也可以使用下面三种方式打开VBE编辑器:■ 在任一工作表标签上单击鼠标右键,在弹出的菜单中选择“查看代码”,则可进入VBE编辑器访问该工作表的代码模块,如图00-03所示;■ 在工作簿窗口左上角的Excel图标上单击鼠标右键,在弹出的菜单中选择“查看代码”,则可进入VBE编辑器访问活动工作簿的ThisWorkbook代码模块,如图00-04所示;■ 选择菜单“工具——宏——宏”命令打开宏对话框,若该工作簿中有宏程序,则单击该对话框中的“编辑”按钮即可进行VBE编辑器代码模块,如图00-05所示。

VBA操作文件与文件夹的技巧与方法

VBA操作文件与文件夹的技巧与方法

VBA操作文件与文件夹的技巧与方法在计算机编程领域,VBA(Visual Basic for Applications)是一种广泛使用的编程语言,它可用于增强Microsoft Office套件中的各种应用程序,例如Excel、Word和PowerPoint。

在VBA中,文件和文件夹的操作是常见的任务,掌握一些技巧和方法可以提高数据处理和文件管理的效率。

本文将介绍一些VBA操作文件与文件夹的技巧与方法。

首先,让我们来了解如何在VBA中打开、保存和关闭文件。

通过使用Workbooks对象,我们可以轻松地打开和保存Excel工作簿。

下面是一些常用的文件操作函数:1. 打开文件:```vbaWorkbooks.Open("C:\路径\文件名.xlsx")```使用上述代码行,我们可以打开指定路径下的Excel文件。

可以根据需要进行相应的更改,以适应不同的路径和文件名。

2. 保存文件:```vbaActiveWorkbook.SaveAs "C:\路径\文件名.xlsx"```这行代码可以将当前工作簿保存到指定路径。

同样,可以根据需要进行更改。

3. 关闭文件:```vbaActiveWorkbook.Close```使用这个简单的代码行可以关闭当前打开的工作簿。

接下来,让我们探讨如何使用VBA创建、移动和删除文件夹。

通过使用FileSystemObject对象,我们可以执行以下操作:1. 创建文件夹:```vbaDim fs As ObjectSet fs = CreateObject("Scripting.FileSystemObject")fs.CreateFolder ("C:\路径\文件夹名")```这个代码段创建了一个名为“文件夹名”的新文件夹。

同样,你可以根据需要更改路径和文件夹名。

2. 移动文件夹:```vbaName "C:\原路径\旧文件夹名" As "C:\新路径\新文件夹名"```这个代码片段可以将指定路径下的文件夹从原位置移动到新位置。

VBA处理文本文件的方法与示例

VBA处理文本文件的方法与示例

VBA处理文本文件的方法与示例VBA(Visual Basic for Applications)是一种用于自动化任务和处理数据的编程语言。

在日常工作中,我们经常需要处理各种文本文件,如CSV、TXT等。

本文将介绍一些VBA处理文本文件的方法和示例,帮助您更高效地处理和操作文本文件。

方法一:打开和读取文本文件VBA提供了打开和读取文本文件的功能。

您可以使用Open语句打开文件,并使用Input语句逐行读取文件内容。

首先,您需要使用Open语句打开文件,指定打开模式和文件路径:```Open "C:\example.txt" For Input As #1```然后,使用Input语句逐行读取文件内容并进行相应处理:```Dim line As StringDo Until EOF(1)Line Input #1, line' 进行处理操作Loop```通过使用EOF函数,我们可以判断文件是否已读取完毕。

在每次循环中,使用Line Input语句将一行内容读取到line变量中,并在需要时进行处理。

方法二:写入和保存文本文件除了读取文件,VBA还提供了写入和保存文本文件的功能。

您可以使用Open语句打开文件,并使用Print语句写入文件内容。

首先,您需要使用Open语句打开文件,指定打开模式和文件路径:```Open "C:\example.txt" For Output As #1```然后,使用Print语句将内容写入文件:```Print #1, "Hello, World!"```您可以使用Print语句写入任意文本内容。

最后,不要忘记使用Close语句关闭文件:```Close #1```这是一个良好的编程习惯,在操作完成后关闭文件,释放资源。

方法三:处理CSV文件CSV(Comma-Separated Values)文件由逗号分隔的文本组成,广泛应用于数据交换和存储。

VBA中的文件夹管理技巧与示例

VBA中的文件夹管理技巧与示例

VBA中的文件夹管理技巧与示例VBA(Visual Basic for Applications)是一种用于自动化任务和开发应用程序的编程语言。

在处理文件和文件夹时,VBA提供了一些强大的功能来管理和操作它们。

本文将介绍VBA中的文件夹管理技巧,并提供一些示例来帮助读者更好地理解并应用这些技巧。

一、创建新文件夹在VBA中创建一个新文件夹非常简单,只需要使用FileSystemObject的CreateFolder方法即可。

下面的示例代码演示了如何创建名为"NewFolder"的新文件夹。

```vbaSub CreateNewFolder()Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim newFolder As ObjectSet newFolder = fso.CreateFolder("C:\Path\To\NewFolder")Set fso = NothingEnd Sub```以上代码中,我们首先创建了一个FileSystemObject对象,并为其设置了一个别名fso。

接着,使用CreateFolder方法创建了一个名为"NewFolder"的新文件夹,并指定了其完整路径(例如:"C:\Path\To\NewFolder")。

最后,将fso对象设置为Nothing,以释放资源。

二、检查文件夹是否存在在VBA中,我们有时需要检查某个文件夹是否存在,以便进行进一步的操作。

使用FileSystemObject的FolderExists方法可以轻松实现这一功能。

以下示例代码演示了如何检查名为"ExistingFolder"的文件夹是否存在。

```vbaSub CheckFolderExists()Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim folderPath As StringfolderPath = "C:\Path\To\ExistingFolder"If fso.FolderExists(folderPath) ThenMsgBox "Folder exists!"ElseMsgBox "Folder does not exist!"End IfSet fso = NothingEnd Sub```在以上代码中,我们首先创建了一个FileSystemObject对象,并为其设置了一个别名fso。

excelvba的实例-列出文件夹下的文件并执行文件重命名操作

excelvba的实例-列出文件夹下的文件并执行文件重命名操作

一、搜索每个文件夹的文件截图首先要引用Microsoft Scripting Runtime组件。

1、逐一读取文件夹和子文件夹的路径放在excel表的第1列。

2、逐一读取表中的文件夹的路径,找出该文件夹下的全部文件,逐一显示文件的路径在右列的单元格。

使用方法:使用时只要将支持宏的excel表放在需要查找文件的文件夹中Dim arrfilejia(1 To 10000) '创建一个数组空间,用来存放文件名称Dim wenjians '文件夹个数Dim k ’excel表录入的行数。

Public Sub wenjianjia()On Error Resume NextDim path as string '声明文件路径Dim I as integerDim fso As New filesystemobject, fd As folder '创建一个filesystemobject对象和一个文件夹对象If Right(ThisWorkbook.Path, 1) = "\" Then’设置要遍历的文件夹目录,如果没有”\”则加上”\”。

path = ThisWorkbook.PathElsepath = ThisWorkbook.Path & "\" 'End Ifcntfiles = 0k = 5Set fd = fso.getfolder(path) '设置fd文件夹对象searchwenjianjia fd '调用子程序搜索文件Call wenjianEnd SubSub searchwenjianjia(ByVal fd As folder)On Error Resume NextDim fl As fileDim sfd As folderIf fd.subfolders.Count = 0 Then Exit Sub '返回由指定文件夹中所有子文件夹(包括隐藏文件夹和系统文件夹)组成的folders集合For Each sfd In fd.subfolders 'folders集合进行循环查找wenjians = wenjians + 1arrfilejia(wenjians) = sfd.PathSheet1.Cells(k, 1) = arrfilejia(wenjians) & "\"k = k + 1searchwenjianjia sfd '使用递归方法查找下一个文件夹NextEnd Sub‘下面子程序主要是从excel表的第一列读出路径。

ExcelVBA-目录及文件操作汇总

ExcelVBA-目录及文件操作汇总

ExcelVBA-目录及文件操作汇总
主要介绍dir,kill,name,mkdir,rmdir,filecopy及filedialog等
注意:介绍的示例是以正常条件下的,非正常条件的请预先判断或者使用on error容错等手段
不正常条件如:文件不存在的时候使用filecopy,文件打开的时候使用name等。

可以对比fso,看看具体差别
一、dir判断文件或文件夹是否存在
/forum. ... 1258425&pid=8556244
示例:
/forum. ... 1258425&pid=8556257
二、kill 删除文件
/forum. ... 1258425&pid=8556266
三、name 重命名文件名
/forum. ... 1258425&pid=8556267
四、mkdir创建文件夹及rmdir删除文件夹
/forum. ... 1258425&pid=8556271
五、filecopy拷贝文件
/forum. ... 1258425&pid=8556273
六、filedialog文件对话框(第一部分)
/forum. ... 1258425&pid=8556274
六、filedialog文件对话框(第二部分)
/forum. ... 425&pid=8556331
第七部分,部分属性相关的函数
/forum. ... 1258425&pid=8556333
第七部分,部分属性相关的函数-示例/forum. ... 425&pid=8556339。

Excel VBA_文本文件和文件夹操作实例集锦

Excel VBA_文本文件和文件夹操作实例集锦

1,导入文本数据(QueryTables)‘110419.xlsSub daorwb()' 2008-4-19Columns("a:g").ClearContents‘文本文件名放在[y2]单元格,两文件在同一个文件夹With ActiveSheet.QueryTables.Add(Connection:= _"TEXT;" & ThisWorkbook.Path & "\" & [y2], Destination:=Range("A1")).FieldNames = True.PreserveFormatting = True.RefreshStyle = xlInsertDeleteCells.SaveData = True.AdjustColumnWidth = False.TextFilePromptOnRefresh = False.TextFilePlatform = 936.TextFileStartRow = 1.TextFileParseType = xlFixedWidth.TextFileTextQualifier = xlTextQualifierDoubleQuote.TextFileTabDelimiter = True.TextFileColumnDataTypes = Array(2, 1, 1, 1, 1, 1, 1).TextFileFixedColumnWidths = Array(1, 1, 1, 1, 1, 1).TextFileTrailingMinusNumbers = True.Refresh BackgroundQuery:=FalseEnd WithEnd Sub2,从文本文件中复制部分数据(OpenText方法)‘/dispbbs.asp?BoardID=92&ID=28958&replyID=&skin=1 Sub Macro1()' 2007-10-18 (自编宏之四)'从文本文件中复制部分数据‘Book1017.xls+test1017.txtApplication.DisplayAlerts = FalseDim Myflnm$Myflnm = ThisWorkbook.Path & "\test1017.txt"Workbooks.OpenText Filename:=Myflnm, Origin _:=xlWindows, StartRow:=37, DataType:=xlDelimited, TextQualifier:= _xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _Array(2, 1)), TrailingMinusNumbers:=TrueSelection.CurrentRegion.CopyThisWorkbook.Activate[a1].SelectActiveSheet.PasteWindows("test1017.txt").ActivateActiveWorkbook.CloseApplication.DisplayAlerts = TrueEnd Sub3,超链接自动生成(Hyperlink公式中引用单元格)Sub caolj1108()‘超链接1108.xls (自编宏之四)Dim Myr%, aa$, x%Myr = [a65536].End(xlUp).RowFor x = 4 To Myr - 3aa = Cells(x, 1)If aa <> "" And InStr(aa, "小") = 0 And InStr(aa, "月") = 0 ThenCells(x, "n").Formula = "=if(--(right(rc[-13],2))<=50,mid(rc[-13],2,2)&""01-""&mid(rc[-13],2,2)&""50"",mid(rc[-13],2,2) &""51-""&text(mid(rc[-13],3,1)+1,""00"")&""00"")" ‘辅助列公式Cells(x, "o").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-1]&""\""&RIGHT(rc[-14],4)&""\""&rc[-14]&""生產進度明細表.xls"",""進度明細表"")"Cells(x, "p").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-2]&""\""&RIGHT(rc[-15],4)&""\""&rc[-15]&""生產通知單.xls"",rc[-15])"Cells(x, "q").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-3]&""\""&RIGHT(rc[-16],4)&""\""&rc[-16]&""PO.pdf"")"End IfNext xEnd Sub4,批量插入指定文件夹图片(FileSearch 函数)Sub plcrtp1111()(自编宏之四)'批量插入指定文件夹图片Dim myFs As FileSearchDim myPath As StringDim i As Long, n As LongSet myFs = Application.FileSearchmyPath = "C:\My Documents\My Pictures\" '你的图片文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypePhotoDrawFiles.Filename = "*.jpg"If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountMsgBox "该文件夹里有" & n & "个jpg文件"ReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)Cells(i, 1) = myfile(i)NextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = NothingCall Macro1End SubSub Macro1()'Dim Myr%, x%, aa$Myr = [a65536].End(xlUp).RowFor x = 1 To Myraa = Cells(x, 1)Cells(x, 2).SelectActiveSheet.Pictures.Insert (aa)Next xEnd Sub5,查询指定文件夹图片(Pictures.Insert 函数)Book1113.xls (自编宏之四)Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim Myr%, x%, aa$Dim myPath As StringMyr = [a65536].End(xlUp).RowIf Target.Address <> "$D$1" Then Exit SubmyPath = "F:\论坛数据\Excel论坛\未完成\相片\" '你的图片文件夹aa = myPath & [d2] & ".jpg"Cells(2, 6).SelectActiveSheet.Pictures.Insert (aa)End Sub6,导出N列数据到文本文件/dispbbs.asp?BoardID=2&ID=280260&replyID=&skin=0 ‘求修改代码.xls (自编宏之四)Sub 导出N列数据()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j As IntegerDim Data As VariantDim cell As RangeDim Arr, T, x%, fname$, fdir, N%fdir = ThisWorkbook.Path & "\号码"N = 7Filename = fdir & "\" & (N - 6) & ".txt"Range("g5:g1004").Copy [am5]Range("o5:o1004").Copy [an5]Range("t5:t1004").Copy [ao5]Range("z5:z1004").Copy [ap5]Range("am5:ap1004").SelectSet cell = Selectioncols = cell.Columns.Countrows = cell.rows.CountOpen Filename For Output As #1For i = 1 To rowsFor j = 1 To colsData = cell.Cells(i, j).ValueIf IsEmpty(cell.Cells(i, j)) Then Data = " "If j <> cols ThenWrite #1, Data;ElseWrite #1, DataEnd IfNext jNext iClose #1Range("am5:ap1004").ClearContentsEnd Sub7,同文件夹根据文本数据修改(Opentext,分列,Name)‘Mybk1.xls(QQ) (自编宏之五)Sub 批量修改文件名()'同文件夹根据文本文件数据修改'08-02-16Dim OldName As String, NewName As StringDim Myflnm$Dim Myr%, x%, Arr, aa$, bb$On Error Resume NextApplication.DisplayAlerts = FalseMyflnm = ThisWorkbook.Path & "\目录.txt"Workbooks.OpenText Filename:=Myflnm, Origin _:=xlWindows, StartRow:=2, DataType:=xlDelimited, TextQualifier:= _xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _Array(2, 1)), TrailingMinusNumbers:=TrueColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(3, 1)), TrailingMinusNumbers:=TrueSelection.CurrentRegion.CopyThisWorkbook.Activate[a1].SelectActiveSheet.PasteWindows("目录.txt").ActivateActiveWorkbook.CloseMyr = [a65536].End(xlUp).RowArr = Range("a1:b" & Myr)For x = 1 To Myraa = Format(Arr(x, 1), "000")bb = Trim(Arr(x, 2))OldName = ThisWorkbook.Path & "\" & aa & ".swf" '原文件名NewName = ThisWorkbook.Path & "\" & bb & ".swf" '新文件名Name OldName As NewName '在同一个文件夹更改文件名Next xApplication.DisplayAlerts = TrueEnd Sub8,有条件导出文本文件到桌面(Output、Print、Environ)‘aa.xls (自编宏之五)Sub daocuwb0408()Dim rng As Range, cel As Range, Filename$Dim aa$, col%, i%Set rng = Range("f1:ik1")For Each cel In rngIf cel <> " " ThenIf Len(cel) <> 0 Thenaa = Split(cel.Address, "$")(1) ‘取得列的字符col = cel.ColumnFilename = Environ("USERPROFILE") & "\桌面\" & aa & ".txt"Open Filename For Output As #1For i = 26 To 245Data = Cells(i, col).ValuePrint #1, Data ‘按列排列数据Next iClose #1End IfEnd IfNext celEnd Sub9,导出工具(Output、Print、MKDir、Split)‘导出工具0414.xls (自编宏之五)‘/dispbbs.asp?boardID=5&ID=47390&page=1Sub daocuwb0414()Dim myRng, Filename$, data, fDim aa$, n%, i%, Myrc%, Myrh%, Myrj%, wjnm$, shtnm$, m%, bb$, wbnm$Dim Sht1 As Worksheet, Sht2 As Worksheet, wb As WorkbookApplication.ScreenUpdating = FalseSet wb = ThisWorkbookSet Sht1 = wb.Sheets("Sheet1")Myrc = [c5].CurrentRegion.Rows.Count + 4Myrh = [h65536].End(xlUp).RowMyrj = [j65536].End(xlUp).RowmyRng = Range("h5:h" & Myrh)For x = 5 To Myrjf = Dir(Cells(x, "j"), vbDirectory) '判断文件夹是否已经存在If f = "" Then MkDir (Cells(x, "j")) '如果不存在就建立Next xFor x = 5 To MyrcSht1.Activatem = 0wjnm = Split(Sht1.Cells(x, 3), ",")(0) '动态工作簿文件名shtnm = Split(Sht1.Cells(x, 3), ",")(1) '动态工作表名bb = Left(wjnm, Len(wjnm) - 4)cc = Len(bb) - Len(Replace(bb, "\", ""))wbnm = Split(bb, "\")(cc)Workbooks.Open wjnmSet Sht2 = ActiveWorkbook.Sheets(shtnm)Sht2.ActivateFor y = 5 To Myrhm = m + 1: col = ""Filename = Sht1.Cells(y, "j") & wbnm & ".txt"Range("bh:bh").ClearContentsColumns("bh:bh").NumberFormatLocal = "@"f1 = Split(Sht1.Cells(y, "h"), ":")(0) '判断列号For y1 = 1 To Len(f1)temp = Mid(f1, y1, 1)If temp Like "[A-Za-z]" Thencol = col & temp '动态区域列号End IfNext y1n = Cells(65536, col).End(xlUp).RowRange(Cells(1, "bh"), Cells(n, "bh")) = Range(Cells(1, col), Cells(n, col)).ValueSet rng = Range(Cells(1, "bh"), Cells(n, "bh"))Open Filename For Output As #1For i = 1 To ndata = Cells(i, "bh").ValueIf data = "" Then GoTo 100Print #1, data '按列排列数据100:Next iClose #1Stop '如果不要暂停,在此行前面加'Next yActiveWorkbook.Close FalseNext xApplication.ScreenUpdating = TrueEnd Sub用山版主部分数组代码替换,速度可加快很多Sub daocuwb0414()Dim myRng, Filename$, data, fDim aa$, n%, i%, Myrc%, Myrh%, Myrj%, wjnm$, shtnm$, m%, bb$, wbnm$Dim Sht1 As Worksheet, Sht2 As Worksheet, wb As WorkbookApplication.ScreenUpdating = FalseSet wb = ThisWorkbookSet Sht1 = wb.Sheets("Sheet1")Myrc = [c5].CurrentRegion.Rows.Count + 4Myrh = [h65536].End(xlUp).RowMyrj = [j65536].End(xlUp).RowmyRng = Range("h5:h" & Myrh)For x = 5 To Myrjf = Dir(Cells(x, "j"), vbDirectory) '判断文件夹是否已经存在If f = "" Then MkDir (Cells(x, "j")) '如果不存在就建立Next xFor x = 5 To MyrcSht1.Activatem = 0wjnm = Split(Sht1.Cells(x, 3), ",")(0) '动态工作簿文件名shtnm = Split(Sht1.Cells(x, 3), ",")(1) '动态工作表名bb = Left(wjnm, Len(wjnm) - 4)cc = Len(bb) - Len(Replace(bb, "\", "")) ‘计算子目录数wbnm = Split(bb, "\")(cc)Workbooks.Open wjnmSet Sht2 = ActiveWorkbook.Sheets(shtnm)Sht2.ActivateFor y = 5 To Myrhm = m + 1: col = ""Filename = Sht1.Cells(y, "j") & wbnm & ".txt"Range("bh:bh").ClearContentsColumns("bh:bh").NumberFormatLocal = "@"f1 = Split(Sht1.Cells(y, "h"), ":")(0) '判断列号For y1 = 1 To Len(f1)temp = Mid(f1, y1, 1)If temp Like "[A-Za-z]" Thencol = col & temp '动态区域列号End IfNext y1n = Cells(65536, col).End(xlUp).RowRange(Cells(1, "bh"), Cells(n, "bh")) = Range(Cells(1, col), Cells(n, col)).ValueSet rng = Range(Cells(1, "bh"), Cells(n, "bh"))'山版主代码运用数组及join函数一次转换连接成文本arr = WorksheetFunction.Transpose(Range(Cells(3, "bh"), Cells(n, "bh"))) '把当列数据(从第3行开始)保存到数组ctxt = Join(arr, Chr(13) & Chr(10)) '连接为文本Do While InStr(ctxt, " ") > 0 '删除空格ctxt = Replace(ctxt, " ", "")LoopDo While InStr(ctxt, Chr(13) & Chr(10) & Chr(13) & Chr(10)) > 0ctxt = Replace(ctxt, Chr(13) & Chr(10) & Chr(13) & Chr(10), Chr(13) & Chr(10))LoopOpen Filename For Output As #1'Open cPath2(i, 1) & Replace(MyName, ".xls", ".txt") For Output As #1 '打开文本文件Print #1, ctxt '将数据一次写入文本文件Close #1 '关闭文本文件Next yActiveWorkbook.Close FalseNext xApplication.ScreenUpdating = TrueEnd Sub10,文本数据逐行导入(文本导入、不重复值、自定义格式、自定义条件格式)‘/dispbbs.asp?boardID=2&ID=247693&page=1&px=0‘要生成的GB-LOAD样式.xls (自编宏之三)Dim Myr%, x%, n%, r1, Myc%, aa, bb, res, y%Dim Sht1 As WorksheetDim Sht2 As WorksheetSub sujcl()' 数据处理' 蓝桥玄霜2007-6-20Application.ScreenUpdating = FalseSet Sht1 = Sheets(1)Set Sht2 = Sheets(2)Sht1.Activate[a1].SelectSht1.Cells.ClearContentsCall ImportRangen = 2Myr = [a65536].End(xlUp).RowColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(9, 1), Array(23, 1)), TrailingMinusNumbers:= _TrueRange("A2:A" & Myr).SelectSelection.Cut Destination:=Range("A3:A" & Myr + 1)Call qukh ‘删除表1的空白行Call fuz0619 ‘复制数据到表2Application.ScreenUpdating = TrueEnd SubSub ImportRange()'引用自"VBA入门与实战"Dim cell As RangeDim Filename As StringDim x As Long, y As IntegerDim str As String, temp As StringDim Data As VariantDim i As IntegerOn Error Resume NextSet cell = ActiveCellFilename = ThisWorkbook.Path & "\GB LOAD.txt"Open Filename For Input As #1If Err <> 0 ThenMsgBox "无法找到" & Filename, vbCritical, "ERROR"Exit SubEnd Ifx = 0y = 0str = ""Application.ScreenUpdating = False '忽略屏幕刷新Do Until EOF(1)Line Input #1, DataFor i = 1 To Len(Data)temp = Mid(Data, i, 1)If temp = "," ThenActiveCell.Offset(x, y) = stry = y + 1str = ""ElseIf i = Len(Data) ThenIf temp <> Chr(34) Then str = str & tempActiveCell.Offset(x, y) = strstr = ""ElseIf temp <> Chr(34) Thenstr = str & tempEnd IfNext iy = 0x = x + 1LoopClose #1Application.ScreenUpdating = TrueEnd SubSub fuz0619()'复制' 蓝桥玄霜2007-6-20'Dim Myr%, x%, n%, r1, Myc%, aa, resDim Sht1 As WorksheetDim Sht2 As WorksheetApplication.ScreenUpdating = FalseSet Sht1 = Sheets(1)Set Sht2 = Sheets(2)n = 2Sht1.ActivateMyr = [a65536].End(xlUp).RowSht2.Activate[b1] = 1: [c1] = 2Range("b1:c1").AutoFill Range("b1:q1")Sht1.ActivateCall UniquedataFor y = 0 To bbFor x = 3 To Myr + 1If Sht1.Cells(x, 1) <> "" ThenIf Sht1.Cells(x, 1) = Sht1.Cells(y + 3, 8) ThenIf Sht1.Cells(x, 1) <> Sht1.Cells(x - 1, 1) ThenSht2.Cells(n, 1) = Cells(x, 1)End Ifaa = Cells(x, 2)Set r1 = Sht2.Range("a1:q1").Find(aa)If Not r1 Is Nothing ThenMyc = r1.ColumnSht2.Cells(n, Myc) = Cells(x, 3)End IfElseGoTo 100End IfEnd If100:Next xn = n + 1Next ySht2.ActivateMyr = [a65536].End(xlUp).RowRange("b2:q" & Myr).SelectSelection.NumberFormatLocal = "0%"Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="0.8"Selection.FormatConditions(1).Interior.ColorIndex = 3Application.ScreenUpdating = TrueEnd SubSub Uniquedata()'不重复值'引用自实战精粹Dim Cel As Range, d, i%Set d = CreateObject("Scripting.Dictionary")Set Sht1 = Sheets(1)n = 3Sht1.ActivateMyr = [a65536].End(xlUp).RowFor Each Cel In Sht1.Range("a3:a" & Myr)If Cel <> "" ThenIf Not d.exists(Cel.Value) Thend.Add Cel.Value, Cel.ValueEnd IfEnd IfNextres = d.Itemsbb = UBound(res)For x = 0 To bbCells(n, 8) = res(x)n = n + 1Next xEnd SubSub qukh()'去除表1空白行'2007/6/20Application.ScreenUpdating = FalseSet Sht1 = Sheets(1)Myr = [a65536].End(xlUp).RowFor x = 3 To MyrIf Left(Cells(x, 1), 1) <> "B" ThenCells(x, 1).EntireRow.Delete shift:=xlUpMyr = Myr - 1: x = x - 1If x > Myr Then Exit SubEnd IfNext xApplication.ScreenUpdating = TrueEnd Sub11,按日期段和条件导出数据,另存为文件‘/dispbbs.asp?boardID=5&ID=27397&page=1‘5550925.xls (自编宏之三)Option ExplicitDim x%, n1%Dim Sht1 As Worksheet, Sht As WorksheetSub daocu()Dim ksrq As Date, jsrq As DateDim ksnm$, jsnm$, n, nn, nmDim Myr%, arr1, y%, i%Dim sFilenm$Application.ScreenUpdating = FalseIf UserForm1.TextBox1.Value = "" Or UserForm1.TextBox2.V alue = "" Then Exit Sub Set Sht1 = Sheets("Sheet3")Sht1.ActivateRange(Cells(2, 1), Cells(2000, 26)).ClearContentsksrq = UserForm1.TextBox1.Valuejsrq = UserForm1.TextBox2.Valuen = DateDiff("m", ksrq, jsrq) + 1ksnm = Right(Year(ksrq), 2) & Application.WorksheetFunction.Text(Month(ksrq), "00") jsnm = Right(Year(jsrq), 2) & Application.WorksheetFunction.Text(Month(jsrq), "00") ReDim nn(1 To n)ReDim nm(1 To n)For i = 1 To nIf i = 1 Thennm(1) = ksnm: nn(1) = CInt(ksnm)Elsenn(i) = nn(i - 1) + 1If Right(nn(i), 2) = "13" Then nn(i) = nn(i) + 100 - 12nm(i) = Application.WorksheetFunction.Text(nn(i), "0000") End IfNext in1 = 2For i = 1 To UBound(nn)For Each Sht In SheetsIf = nm(i) ThenSht.ActivateMyr = [a65536].End(xlUp).RowFor x = 2 To MyrIf Cells(x, 2) >= ksrq And Cells(x, 2) <= jsrq ThenCall daocu1n1 = n1 + 1End IfNext xEnd IfNext ShtNext iSht1.ActivateApplication.ScreenUpdating = TrueSht1.CopysFilenm = Application.GetSaveAsFilename(filefilter:="Excel files (*.xls),*.xls") ActiveWorkbook.SaveAs sFilenm, xlTextMsgBox "数据已导出! "End SubSub daocu1()'选择导出Dim xx%For xx = 0 To 25If UserForm1.ListBox1.Selected(xx) = True ThenCells(x, xx + 1).Copy Sht1.Cells(n1, xx + 1)End IfNext xxEnd Sub12,导出到多文本文件Sub dcdwb()'导出到文本文件(自编宏之二)‘请赐教0608.xls‘/dispbbs.asp?boardID=2&ID=245438&page=1&px=0 '2007/6/8Dim Filename$, Data$, aa$,Mypa$Dim rows As Long, cols%Dim i%, j%, Myr%, rr%, add%, n%Dim cell As RangeApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).Row: n = 2Range("A1").SelectIf [a1] = "★" Then aa = [b1]Do Until ActiveCell.Row > MyrCells.Find(What:="★", After:=ActiveCell).Activaterr = ActiveCell.RowActiveCell.Offset(-rr + n, 1).Resize(rr - n, 1).SelectSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.CountFilename = Mypa & aa & ".txt" ‘文件名Open Filename For Output As #1For i = 1 To rowsData = cell.Cells(i, cols) '一列数据If IsEmpty(cell.Cells(i, cols)) Then Data = ""Print #1, (Data) '字符串型可去除""Next iClose #1ActiveCell.Offset(rr - n, -1).Resize(1, 1).Selectaa = Cells(rr, 2).Text ‘文件名n = rr + 1LoopApplication.ScreenUpdating = TrueEnd SubSub dcdwb2()'导出到一个文本文件'水平数据'2007/6/8Dim Filename$, Data$, aa$, Mypa$Dim rows As Long, cols%, cols1%Dim i%, j%, Myr%, rr%, add%, n%Dim cell As RangeApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).Row: n = 2Range("A1").SelectIf [a1] = "★" Then aa = [b1]Filename = Mypa & aa & ".txt"Open Filename For Append As #1Do Until ActiveCell.Row > MyrCells.Find(What:="★", After:=ActiveCell).Activaterr = ActiveCell.RowActiveCell.Offset(-rr + n - 1, 1).Resize(rr - n + 1, 1).SelectSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.CountSelection.CopyRange("H1").SelectSelection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _ , Transpose:=TrueApplication.CutCopyMode = Falsecols = cols + 7cols1 = rows + 7For i = cols To cols1Data = Cells(1, i) '一单元格的数据If IsEmpty(Cells(1, i)) Then Data = ""If i <> cols1 ThenPrint #1, (Data) & " "; '数据没有"",加空格(如果用Write #1,Data; 则文本中数据有””)ElsePrint #1, (Data)End IfNext iSelection.ClearContentsCells(rr, 1).Selectn = rr + 1LoopClose #1Application.ScreenUpdating = TrueEnd Sub‘/viewthread.php?tid=596265&pid=4001678&page=1&extra=page%3D 1Sub dcdwb()Dim Filename$, Data$, aa$, Mypa$, ArrDim rows As Long, col%Dim i%, j%, Myr%, rr%, nApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).RowArr = Range("a1:c" & Myr)For i = 1 To UBound(Arr) Step 4n = 0: col = col + 1Filename = Mypa & col & ".txt" '文件名Open Filename For Output As #1For rr = i To i + 4If rr > Myr Then Data = "" & vbTab & "" & vbTab & n: Print #1, (Data): Exit ForIf rr <> i + 4 ThenData = Arr(rr, 1) & vbTab & Arr(rr, 2) & vbTab & Arr(rr, 3)n = n + Arr(rr, 3)ElseData = "" & vbTab & "" & vbTab & nEnd IfPrint #1, (Data)NextClose #1NextApplication.ScreenUpdating = TrueEnd Sub13,导入文本文件(用文本文件名为新表命名)Sub Drwbwj()' 导入文本文件,用文本文件名为新表命名‘导入文本文件.xls (自编宏之一)' by:蓝桥玄霜' 2007-3-7‘/dispbbs.asp?boardid=5&id=13592Dim Mystr As StringDim filename '文件路径'选取文件Application.ScreenUpdating = FalseOn Error GoTo 100Dofilename = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "请选择文件", , MultiSelect:=False)ActiveWorkbook.Worksheets.Add '把文本文件导入Excel新表"TEXT;" & filename, Destination:=Range("A1")).Refresh BackgroundQuery:=FalseEnd With[j2] = filename '以下为获取文件名,给新表命名[j3].SelectActiveCell.FormulaR1C1 = _"=RIGHT(R[-1]C,LEN(R[-1]C)-FIND(""/"",SUBSTITUTE(R[-1]C,""\"",""/"",LEN(R[-1]C)-LEN (SUBSTITUTE(R[-1]C,""\"","""")))))"[j4].SelectActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,LEN(R[-1]C)-4)"Mystr = [j4]'MsgBox Mystr = MystrRange("j2:j4").ClearContents '删除辅助列Loop Until filename = FalseGoTo 200100:Application.DisplayAlerts = False ‘不使报警ActiveWindow.SelectedSheets.DeleteApplication.DisplayAlerts = True200:Application.ScreenUpdating = TrueEnd SubSub LxDrwbwj()' 连续导入文本文件‘导入后.xls' by:蓝桥玄霜' 2007-3-19Dim filename ‘文件路径Dim Myr1%, n%Application.ScreenUpdating = FalseOn Error GoTo 200ActiveWorkbook.Worksheets("Sheet1").Activate '激活表1n = 1Dofilename = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "请选取文件", , MultiSelect:=False) ‘选取文本文件"TEXT;" & filename, Destination:=Range("A" & n)).Refresh BackgroundQuery:=FalseIf n > 1 ThenRange("a" & n).EntireRow.Delete ‘第二个表头行删除End IfMyr1 = [a1].End(xlDown).Rown = Myr1 + 1End WithLoop Until filename = False200:Application.ScreenUpdating = TrueEnd Sub14,导出到文本文件‘2007314‘体彩3D分析.xls (自编宏之一)‘先选择要导出的数据Private Sub CommandButton1_Click()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j As IntegerDim Data As StringDim cell As RangeSet cell = Selection ‘选择数据cols = cell.Columns.Countrows = cell.rows.CountFilename = "G:\Excel论坛\精英培训\数据0313.txt"Open Filename For Output As #1For i = 1 To rowsData = cell.Cells(i, cols) ‘一列数据If IsEmpty(cell.Cells(i, cols)) Then Data = ""Print #1, (Data) ‘字符串型可去除””‘如果用Write #1 Data,输出的是”200365”Next iClose #1End Sub15,导出指定区域数据到文本文件,路径可选择(GetSaveAsFilename)‘/dispbbs.asp?boardID=2&ID=316431&page=1&px=0Private Sub CommandButton1_Click()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j%Dim Data As StringDim cell As RangeSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.Count‘Filename = Application.GetSaveAsFilename("Text files (*.txt),*.txt")DoFilename = Application.GetSaveAsFilenameLoop Until Filename <> FalseOpen Filename For Output As #1For i = 1 To rowsFor j = 1 To colsData = cell.Cells(i, j) & " "If j = cols Then Print #1, (Data): GoTo 100Print #1, (Data);Next j100:Next iClose #1End Sub16,导入指定文件夹的文本文件(包括子文件夹),用文本文件名为新表命名,FileSearch,分列Sub pldrwb0423()‘inandout.xls EP'批量导入指定文件夹文本文件Dim myFs As FileSearchDim myPath As String, Filename$Dim i As Long, n As LongSet myFs = Application.FileSearchmyPath = ThisWorkbook.Path & "\source\" '你的文本文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypeNoteItem.Filename = "*.txt".SearchSubFolders = True '同时也搜索子文件夹If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)Filename = myfile(i)aa = InStrRev(Filename, "\")nm = Right(Filename, Len(Filename) - aa)nm = Left(nm, Len(nm) - 4)ActiveWorkbook.Worksheets.Add '把文本文件导入Excel新表With ActiveSheet.QueryTables.Add(Connection:= _"TEXT;" & Filename, Destination:=Range("A1")).Refresh BackgroundQuery:=FalseEnd With = nmColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), Space:=True, FieldInfo _:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True[a1].SelectNextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = NothingEnd Sub17,批量删除同文件夹里指定工作簿文件,‘/dispbbs.asp?boardid=5&id=87719&star=1#1101674Sub plsc0119()'批量删除指定的文件Dim myFs As FileSearchDim myPath As String, Filename$Dim i As Long, n As Long, myFileSet myFs = Application.FileSearchmyPath = ThisWorkbook.Path '你的文本文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypeNoteItem.Filename = "*.xls"If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountReDim myFile(1 To n) As StringFor i = 1 To nmyFile(i) = .FoundFiles(i)If InStr(myFile(i), "一月") > 0 Or InStr(myFile(i), "二月") > 0 Or InStr(myFile(i), "三月") > 0 ThenKill myFile(i)End IfNextEnd IfEnd WithEnd Sub18,统计文件夹里子文件夹名及所有的文件名‘/viewthread.php?tid=393673&page=1&extra=page%3D1‘示例.rarSub wjjm()'文件夹名Dim fso, f, fc, myPath$, i%, myFolSet fso = CreateObject("Scripting.FileSystemObject")myPath = ThisWorkbook.pathSet f = fso.GetFolder(myPath)Set fc = f.SubFoldersFor Each myFol In fci = i + 1Cells(i, 1) = NextSet fso = NothingEnd SubSub wjjm()'同目录下文件名(Files对象)Dim fso, f, fc, myPath$, i%, myFolSet fso = CreateObject("Scripting.FileSystemObject")myPath = ThisWorkbook.PathSet f = fso.GetFolder(myPath)Set fc = f.FilesFor Each myFol In fcIf Right(, 3) = "xls" Theni = i + 1Cells(i, 1) = End IfNextSet fso = NothingEnd Sub19,对文件夹里没有后缀名的文件加”.txt”后缀‘2009-5-4 EPSub tjwjjwj()'统计文件夹文件Dim myFs As FileSearchDim myPath As StringDim i As Long, n As LongSet myFs = Application.FileSearchmyPath = ThisWorkbook.pathWith myFs.NewSearch.LookIn = myPath.SearchSubFolders = TrueIf .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountMsgBox "该文件夹里有" & n & "个文件"ReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)aa = InStrRev(myfile(i), "\")nm = Right(Myfile(i), Len(Myfile(i)) - aa)‘nm = Left(nm, Len(nm) - 4)Cells(i, 1) = nmNextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = Nothing。

Excel VBA操作文本文档TXT文件的方法(一)

Excel VBA操作文本文档TXT文件的方法(一)

VBA使用FileSystemObject将读取或写入文本文件(一)有时,我们需要将一个文本文件中的数据读取到Excel单元格中,或将指定单元格的内容按指定的格式导出到文本文件中,这时,我们就需要使用Scripting.FileSystemObject对象来进行操作。

在接下来的几篇里我们介绍如何使用FileSystemObject对象操作文本文件的。

工欲善其事,必先利其器,那么我们就先花几篇文章来详细介绍下FileSystemObject对象。

一、如何创建FileSystemObject对象在VBA中,是通过CreateObject函数返回FileSystemObject对象。

示例:Dim fso As ObjectSet fso=CreateObject("Scripting.FileSystemObject")二、FileSystemObject主要方法介绍1、CreateTextFile方法:用于创建一个指定文件名,并返回一个可操作的TextStream对象。

语法:object.CreateTextFile(filename[,overwrite[,unicode]])示例1:在C:\FSOTest\中创建一个名为testFile的文本文件,并写入一行“CreateTextFile Test”:Sub CreateFile()Dim sFile As Object, FSO As ObjectSet FSO = CreateObject("Scripting.FileSystemObject")Set sFile = FSO.CreateTextFile("C:\FSOTest\TestFile.txt",True)sFile.WriteLine ("CreateTextFile Test")sFile.CloseSet sFile = NothingSet FSO = NothingEnd Sub2、DeleteFile方法:用于删除一个指定的文件。

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1,导入文本数据(QueryTables)‘110419.xlsSub daorwb()' 2008-4-19Columns("a:g").ClearContents‘文本文件名放在[y2]单元格,两文件在同一个文件夹With ActiveSheet.QueryTables.Add(Connection:= _"TEXT;" & ThisWorkbook.Path & "\" & [y2], Destination:=Range("A1")).FieldNames = True.PreserveFormatting = True.RefreshStyle = xlInsertDeleteCells.SaveData = True.AdjustColumnWidth = False.TextFilePromptOnRefresh = False.TextFilePlatform = 936.TextFileStartRow = 1.TextFileParseType = xlFixedWidth.TextFileTextQualifier = xlTextQualifierDoubleQuote.TextFileTabDelimiter = True.TextFileColumnDataTypes = Array(2, 1, 1, 1, 1, 1, 1).TextFileFixedColumnWidths = Array(1, 1, 1, 1, 1, 1).TextFileTrailingMinusNumbers = True.Refresh BackgroundQuery:=FalseEnd WithEnd Sub2,从文本文件中复制部分数据(OpenText方法)‘/dispbbs.asp?BoardID=92&ID=28958&replyID=&skin=1 Sub Macro1()' 2007-10-18 (自编宏之四)'从文本文件中复制部分数据‘Book1017.xls+test1017.txtApplication.DisplayAlerts = FalseDim Myflnm$Myflnm = ThisWorkbook.Path & "\test1017.txt"Workbooks.OpenText Filename:=Myflnm, Origin _:=xlWindows, StartRow:=37, DataType:=xlDelimited, TextQualifier:= _xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _Array(2, 1)), TrailingMinusNumbers:=TrueSelection.CurrentRegion.CopyThisWorkbook.Activate[a1].SelectActiveSheet.PasteWindows("test1017.txt").ActivateActiveWorkbook.CloseApplication.DisplayAlerts = TrueEnd Sub3,超链接自动生成(Hyperlink公式中引用单元格)Sub caolj1108()‘超链接1108.xls (自编宏之四)Dim Myr%, aa$, x%Myr = [a65536].End(xlUp).RowFor x = 4 To Myr - 3aa = Cells(x, 1)If aa <> "" And InStr(aa, "小") = 0 And InStr(aa, "月") = 0 ThenCells(x, "n").Formula = "=if(--(right(rc[-13],2))<=50,mid(rc[-13],2,2)&""01-""&mid(rc[-13],2,2)&""50"",mid(rc[-13],2,2) &""51-""&text(mid(rc[-13],3,1)+1,""00"")&""00"")" ‘辅助列公式Cells(x, "o").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-1]&""\""&RIGHT(rc[-14],4)&""\""&rc[-14]&""生產進度明細表.xls"",""進度明細表"")"Cells(x, "p").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-2]&""\""&RIGHT(rc[-15],4)&""\""&rc[-15]&""生產通知單.xls"",rc[-15])"Cells(x, "q").Formula = "=HYPERLINK(""\\Tfknit\texford\生產通知單類\2007生產通知單\""&rc[-3]&""\""&RIGHT(rc[-16],4)&""\""&rc[-16]&""PO.pdf"")"End IfNext xEnd Sub4,批量插入指定文件夹图片(FileSearch 函数)Sub plcrtp1111()(自编宏之四)'批量插入指定文件夹图片Dim myFs As FileSearchDim myPath As StringDim i As Long, n As LongSet myFs = Application.FileSearchmyPath = "C:\My Documents\My Pictures\" '你的图片文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypePhotoDrawFiles.Filename = "*.jpg"If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountMsgBox "该文件夹里有" & n & "个jpg文件"ReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)Cells(i, 1) = myfile(i)NextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = NothingCall Macro1End SubSub Macro1()'Dim Myr%, x%, aa$Myr = [a65536].End(xlUp).RowFor x = 1 To Myraa = Cells(x, 1)Cells(x, 2).SelectActiveSheet.Pictures.Insert (aa)Next xEnd Sub5,查询指定文件夹图片(Pictures.Insert 函数)Book1113.xls (自编宏之四)Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim Myr%, x%, aa$Dim myPath As StringMyr = [a65536].End(xlUp).RowIf Target.Address <> "$D$1" Then Exit SubmyPath = "F:\论坛数据\Excel论坛\未完成\相片\" '你的图片文件夹aa = myPath & [d2] & ".jpg"Cells(2, 6).SelectActiveSheet.Pictures.Insert (aa)End Sub6,导出N列数据到文本文件/dispbbs.asp?BoardID=2&ID=280260&replyID=&skin=0 ‘求修改代码.xls (自编宏之四)Sub 导出N列数据()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j As IntegerDim Data As VariantDim cell As RangeDim Arr, T, x%, fname$, fdir, N%fdir = ThisWorkbook.Path & "\号码"N = 7Filename = fdir & "\" & (N - 6) & ".txt"Range("g5:g1004").Copy [am5]Range("o5:o1004").Copy [an5]Range("t5:t1004").Copy [ao5]Range("z5:z1004").Copy [ap5]Range("am5:ap1004").SelectSet cell = Selectioncols = cell.Columns.Countrows = cell.rows.CountOpen Filename For Output As #1For i = 1 To rowsFor j = 1 To colsData = cell.Cells(i, j).ValueIf IsEmpty(cell.Cells(i, j)) Then Data = " "If j <> cols ThenWrite #1, Data;ElseWrite #1, DataEnd IfNext jNext iClose #1Range("am5:ap1004").ClearContentsEnd Sub7,同文件夹根据文本数据修改(Opentext,分列,Name)‘Mybk1.xls(QQ) (自编宏之五)Sub 批量修改文件名()'同文件夹根据文本文件数据修改'08-02-16Dim OldName As String, NewName As StringDim Myflnm$Dim Myr%, x%, Arr, aa$, bb$On Error Resume NextApplication.DisplayAlerts = FalseMyflnm = ThisWorkbook.Path & "\目录.txt"Workbooks.OpenText Filename:=Myflnm, Origin _:=xlWindows, StartRow:=2, DataType:=xlDelimited, TextQualifier:= _xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _Array(2, 1)), TrailingMinusNumbers:=TrueColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(3, 1)), TrailingMinusNumbers:=TrueSelection.CurrentRegion.CopyThisWorkbook.Activate[a1].SelectActiveSheet.PasteWindows("目录.txt").ActivateActiveWorkbook.CloseMyr = [a65536].End(xlUp).RowArr = Range("a1:b" & Myr)For x = 1 To Myraa = Format(Arr(x, 1), "000")bb = Trim(Arr(x, 2))OldName = ThisWorkbook.Path & "\" & aa & ".swf" '原文件名NewName = ThisWorkbook.Path & "\" & bb & ".swf" '新文件名Name OldName As NewName '在同一个文件夹更改文件名Next xApplication.DisplayAlerts = TrueEnd Sub8,有条件导出文本文件到桌面(Output、Print、Environ)‘aa.xls (自编宏之五)Sub daocuwb0408()Dim rng As Range, cel As Range, Filename$Dim aa$, col%, i%Set rng = Range("f1:ik1")For Each cel In rngIf cel <> " " ThenIf Len(cel) <> 0 Thenaa = Split(cel.Address, "$")(1) ‘取得列的字符col = cel.ColumnFilename = Environ("USERPROFILE") & "\桌面\" & aa & ".txt"Open Filename For Output As #1For i = 26 To 245Data = Cells(i, col).ValuePrint #1, Data ‘按列排列数据Next iClose #1End IfEnd IfNext celEnd Sub9,导出工具(Output、Print、MKDir、Split)‘导出工具0414.xls (自编宏之五)‘/dispbbs.asp?boardID=5&ID=47390&page=1Sub daocuwb0414()Dim myRng, Filename$, data, fDim aa$, n%, i%, Myrc%, Myrh%, Myrj%, wjnm$, shtnm$, m%, bb$, wbnm$Dim Sht1 As Worksheet, Sht2 As Worksheet, wb As WorkbookApplication.ScreenUpdating = FalseSet wb = ThisWorkbookSet Sht1 = wb.Sheets("Sheet1")Myrc = [c5].CurrentRegion.Rows.Count + 4Myrh = [h65536].End(xlUp).RowMyrj = [j65536].End(xlUp).RowmyRng = Range("h5:h" & Myrh)For x = 5 To Myrjf = Dir(Cells(x, "j"), vbDirectory) '判断文件夹是否已经存在If f = "" Then MkDir (Cells(x, "j")) '如果不存在就建立Next xFor x = 5 To MyrcSht1.Activatem = 0wjnm = Split(Sht1.Cells(x, 3), ",")(0) '动态工作簿文件名shtnm = Split(Sht1.Cells(x, 3), ",")(1) '动态工作表名bb = Left(wjnm, Len(wjnm) - 4)cc = Len(bb) - Len(Replace(bb, "\", ""))wbnm = Split(bb, "\")(cc)Workbooks.Open wjnmSet Sht2 = ActiveWorkbook.Sheets(shtnm)Sht2.ActivateFor y = 5 To Myrhm = m + 1: col = ""Filename = Sht1.Cells(y, "j") & wbnm & ".txt"Range("bh:bh").ClearContentsColumns("bh:bh").NumberFormatLocal = "@"f1 = Split(Sht1.Cells(y, "h"), ":")(0) '判断列号For y1 = 1 To Len(f1)temp = Mid(f1, y1, 1)If temp Like "[A-Za-z]" Thencol = col & temp '动态区域列号End IfNext y1n = Cells(65536, col).End(xlUp).RowRange(Cells(1, "bh"), Cells(n, "bh")) = Range(Cells(1, col), Cells(n, col)).ValueSet rng = Range(Cells(1, "bh"), Cells(n, "bh"))Open Filename For Output As #1For i = 1 To ndata = Cells(i, "bh").ValueIf data = "" Then GoTo 100Print #1, data '按列排列数据100:Next iClose #1Stop '如果不要暂停,在此行前面加'Next yActiveWorkbook.Close FalseNext xApplication.ScreenUpdating = TrueEnd Sub用山版主部分数组代码替换,速度可加快很多Sub daocuwb0414()Dim myRng, Filename$, data, fDim aa$, n%, i%, Myrc%, Myrh%, Myrj%, wjnm$, shtnm$, m%, bb$, wbnm$Dim Sht1 As Worksheet, Sht2 As Worksheet, wb As WorkbookApplication.ScreenUpdating = FalseSet wb = ThisWorkbookSet Sht1 = wb.Sheets("Sheet1")Myrc = [c5].CurrentRegion.Rows.Count + 4Myrh = [h65536].End(xlUp).RowMyrj = [j65536].End(xlUp).RowmyRng = Range("h5:h" & Myrh)For x = 5 To Myrjf = Dir(Cells(x, "j"), vbDirectory) '判断文件夹是否已经存在If f = "" Then MkDir (Cells(x, "j")) '如果不存在就建立Next xFor x = 5 To MyrcSht1.Activatem = 0wjnm = Split(Sht1.Cells(x, 3), ",")(0) '动态工作簿文件名shtnm = Split(Sht1.Cells(x, 3), ",")(1) '动态工作表名bb = Left(wjnm, Len(wjnm) - 4)cc = Len(bb) - Len(Replace(bb, "\", "")) ‘计算子目录数wbnm = Split(bb, "\")(cc)Workbooks.Open wjnmSet Sht2 = ActiveWorkbook.Sheets(shtnm)Sht2.ActivateFor y = 5 To Myrhm = m + 1: col = ""Filename = Sht1.Cells(y, "j") & wbnm & ".txt"Range("bh:bh").ClearContentsColumns("bh:bh").NumberFormatLocal = "@"f1 = Split(Sht1.Cells(y, "h"), ":")(0) '判断列号For y1 = 1 To Len(f1)temp = Mid(f1, y1, 1)If temp Like "[A-Za-z]" Thencol = col & temp '动态区域列号End IfNext y1n = Cells(65536, col).End(xlUp).RowRange(Cells(1, "bh"), Cells(n, "bh")) = Range(Cells(1, col), Cells(n, col)).ValueSet rng = Range(Cells(1, "bh"), Cells(n, "bh"))'山版主代码运用数组及join函数一次转换连接成文本arr = WorksheetFunction.Transpose(Range(Cells(3, "bh"), Cells(n, "bh"))) '把当列数据(从第3行开始)保存到数组ctxt = Join(arr, Chr(13) & Chr(10)) '连接为文本Do While InStr(ctxt, " ") > 0 '删除空格ctxt = Replace(ctxt, " ", "")LoopDo While InStr(ctxt, Chr(13) & Chr(10) & Chr(13) & Chr(10)) > 0ctxt = Replace(ctxt, Chr(13) & Chr(10) & Chr(13) & Chr(10), Chr(13) & Chr(10))LoopOpen Filename For Output As #1'Open cPath2(i, 1) & Replace(MyName, ".xls", ".txt") For Output As #1 '打开文本文件Print #1, ctxt '将数据一次写入文本文件Close #1 '关闭文本文件Next yActiveWorkbook.Close FalseNext xApplication.ScreenUpdating = TrueEnd Sub10,文本数据逐行导入(文本导入、不重复值、自定义格式、自定义条件格式)‘/dispbbs.asp?boardID=2&ID=247693&page=1&px=0‘要生成的GB-LOAD样式.xls (自编宏之三)Dim Myr%, x%, n%, r1, Myc%, aa, bb, res, y%Dim Sht1 As WorksheetDim Sht2 As WorksheetSub sujcl()' 数据处理' 蓝桥玄霜2007-6-20Application.ScreenUpdating = FalseSet Sht1 = Sheets(1)Set Sht2 = Sheets(2)Sht1.Activate[a1].SelectSht1.Cells.ClearContentsCall ImportRangen = 2Myr = [a65536].End(xlUp).RowColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(9, 1), Array(23, 1)), TrailingMinusNumbers:= _TrueRange("A2:A" & Myr).SelectSelection.Cut Destination:=Range("A3:A" & Myr + 1)Call qukh ‘删除表1的空白行Call fuz0619 ‘复制数据到表2Application.ScreenUpdating = TrueEnd SubSub ImportRange()'引用自"VBA入门与实战"Dim cell As RangeDim Filename As StringDim x As Long, y As IntegerDim str As String, temp As StringDim Data As VariantDim i As IntegerOn Error Resume NextSet cell = ActiveCellFilename = ThisWorkbook.Path & "\GB LOAD.txt"Open Filename For Input As #1If Err <> 0 ThenMsgBox "无法找到" & Filename, vbCritical, "ERROR"Exit SubEnd Ifx = 0y = 0str = ""Application.ScreenUpdating = False '忽略屏幕刷新Do Until EOF(1)Line Input #1, DataFor i = 1 To Len(Data)temp = Mid(Data, i, 1)If temp = "," ThenActiveCell.Offset(x, y) = stry = y + 1str = ""ElseIf i = Len(Data) ThenIf temp <> Chr(34) Then str = str & tempActiveCell.Offset(x, y) = strstr = ""ElseIf temp <> Chr(34) Thenstr = str & tempEnd IfNext iy = 0x = x + 1LoopClose #1Application.ScreenUpdating = TrueEnd SubSub fuz0619()'复制' 蓝桥玄霜2007-6-20'Dim Myr%, x%, n%, r1, Myc%, aa, resDim Sht1 As WorksheetDim Sht2 As WorksheetApplication.ScreenUpdating = FalseSet Sht1 = Sheets(1)Set Sht2 = Sheets(2)n = 2Sht1.ActivateMyr = [a65536].End(xlUp).RowSht2.Activate[b1] = 1: [c1] = 2Range("b1:c1").AutoFill Range("b1:q1")Sht1.ActivateCall UniquedataFor y = 0 To bbFor x = 3 To Myr + 1If Sht1.Cells(x, 1) <> "" ThenIf Sht1.Cells(x, 1) = Sht1.Cells(y + 3, 8) ThenIf Sht1.Cells(x, 1) <> Sht1.Cells(x - 1, 1) ThenSht2.Cells(n, 1) = Cells(x, 1)End Ifaa = Cells(x, 2)Set r1 = Sht2.Range("a1:q1").Find(aa)If Not r1 Is Nothing ThenMyc = r1.ColumnSht2.Cells(n, Myc) = Cells(x, 3)End IfElseGoTo 100End IfEnd If100:Next xn = n + 1Next ySht2.ActivateMyr = [a65536].End(xlUp).RowRange("b2:q" & Myr).SelectSelection.NumberFormatLocal = "0%"Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="0.8"Selection.FormatConditions(1).Interior.ColorIndex = 3Application.ScreenUpdating = TrueEnd SubSub Uniquedata()'不重复值'引用自实战精粹Dim Cel As Range, d, i%Set d = CreateObject("Scripting.Dictionary")Set Sht1 = Sheets(1)n = 3Sht1.ActivateMyr = [a65536].End(xlUp).RowFor Each Cel In Sht1.Range("a3:a" & Myr)If Cel <> "" ThenIf Not d.exists(Cel.Value) Thend.Add Cel.Value, Cel.ValueEnd IfEnd IfNextres = d.Itemsbb = UBound(res)For x = 0 To bbCells(n, 8) = res(x)n = n + 1Next xEnd SubSub qukh()'去除表1空白行'2007/6/20Application.ScreenUpdating = FalseSet Sht1 = Sheets(1)Myr = [a65536].End(xlUp).RowFor x = 3 To MyrIf Left(Cells(x, 1), 1) <> "B" ThenCells(x, 1).EntireRow.Delete shift:=xlUpMyr = Myr - 1: x = x - 1If x > Myr Then Exit SubEnd IfNext xApplication.ScreenUpdating = TrueEnd Sub11,按日期段和条件导出数据,另存为文件‘/dispbbs.asp?boardID=5&ID=27397&page=1‘5550925.xls (自编宏之三)Option ExplicitDim x%, n1%Dim Sht1 As Worksheet, Sht As WorksheetSub daocu()Dim ksrq As Date, jsrq As DateDim ksnm$, jsnm$, n, nn, nmDim Myr%, arr1, y%, i%Dim sFilenm$Application.ScreenUpdating = FalseIf UserForm1.TextBox1.Value = "" Or UserForm1.TextBox2.V alue = "" Then Exit Sub Set Sht1 = Sheets("Sheet3")Sht1.ActivateRange(Cells(2, 1), Cells(2000, 26)).ClearContentsksrq = UserForm1.TextBox1.Valuejsrq = UserForm1.TextBox2.Valuen = DateDiff("m", ksrq, jsrq) + 1ksnm = Right(Year(ksrq), 2) & Application.WorksheetFunction.Text(Month(ksrq), "00") jsnm = Right(Year(jsrq), 2) & Application.WorksheetFunction.Text(Month(jsrq), "00") ReDim nn(1 To n)ReDim nm(1 To n)For i = 1 To nIf i = 1 Thennm(1) = ksnm: nn(1) = CInt(ksnm)Elsenn(i) = nn(i - 1) + 1If Right(nn(i), 2) = "13" Then nn(i) = nn(i) + 100 - 12nm(i) = Application.WorksheetFunction.Text(nn(i), "0000") End IfNext in1 = 2For i = 1 To UBound(nn)For Each Sht In SheetsIf = nm(i) ThenSht.ActivateMyr = [a65536].End(xlUp).RowFor x = 2 To MyrIf Cells(x, 2) >= ksrq And Cells(x, 2) <= jsrq ThenCall daocu1n1 = n1 + 1End IfNext xEnd IfNext ShtNext iSht1.ActivateApplication.ScreenUpdating = TrueSht1.CopysFilenm = Application.GetSaveAsFilename(filefilter:="Excel files (*.xls),*.xls") ActiveWorkbook.SaveAs sFilenm, xlTextMsgBox "数据已导出! "End SubSub daocu1()'选择导出Dim xx%For xx = 0 To 25If UserForm1.ListBox1.Selected(xx) = True ThenCells(x, xx + 1).Copy Sht1.Cells(n1, xx + 1)End IfNext xxEnd Sub12,导出到多文本文件Sub dcdwb()'导出到文本文件(自编宏之二)‘请赐教0608.xls‘/dispbbs.asp?boardID=2&ID=245438&page=1&px=0 '2007/6/8Dim Filename$, Data$, aa$,Mypa$Dim rows As Long, cols%Dim i%, j%, Myr%, rr%, add%, n%Dim cell As RangeApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).Row: n = 2Range("A1").SelectIf [a1] = "★" Then aa = [b1]Do Until ActiveCell.Row > MyrCells.Find(What:="★", After:=ActiveCell).Activaterr = ActiveCell.RowActiveCell.Offset(-rr + n, 1).Resize(rr - n, 1).SelectSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.CountFilename = Mypa & aa & ".txt" ‘文件名Open Filename For Output As #1For i = 1 To rowsData = cell.Cells(i, cols) '一列数据If IsEmpty(cell.Cells(i, cols)) Then Data = ""Print #1, (Data) '字符串型可去除""Next iClose #1ActiveCell.Offset(rr - n, -1).Resize(1, 1).Selectaa = Cells(rr, 2).Text ‘文件名n = rr + 1LoopApplication.ScreenUpdating = TrueEnd SubSub dcdwb2()'导出到一个文本文件'水平数据'2007/6/8Dim Filename$, Data$, aa$, Mypa$Dim rows As Long, cols%, cols1%Dim i%, j%, Myr%, rr%, add%, n%Dim cell As RangeApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).Row: n = 2Range("A1").SelectIf [a1] = "★" Then aa = [b1]Filename = Mypa & aa & ".txt"Open Filename For Append As #1Do Until ActiveCell.Row > MyrCells.Find(What:="★", After:=ActiveCell).Activaterr = ActiveCell.RowActiveCell.Offset(-rr + n - 1, 1).Resize(rr - n + 1, 1).SelectSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.CountSelection.CopyRange("H1").SelectSelection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _ , Transpose:=TrueApplication.CutCopyMode = Falsecols = cols + 7cols1 = rows + 7For i = cols To cols1Data = Cells(1, i) '一单元格的数据If IsEmpty(Cells(1, i)) Then Data = ""If i <> cols1 ThenPrint #1, (Data) & " "; '数据没有"",加空格(如果用Write #1,Data; 则文本中数据有””)ElsePrint #1, (Data)End IfNext iSelection.ClearContentsCells(rr, 1).Selectn = rr + 1LoopClose #1Application.ScreenUpdating = TrueEnd Sub‘/viewthread.php?tid=596265&pid=4001678&page=1&extra=page%3D 1Sub dcdwb()Dim Filename$, Data$, aa$, Mypa$, ArrDim rows As Long, col%Dim i%, j%, Myr%, rr%, nApplication.ScreenUpdating = FalseMypa = ThisWorkbook.Path & "\"Myr = [b65536].End(xlUp).RowArr = Range("a1:c" & Myr)For i = 1 To UBound(Arr) Step 4n = 0: col = col + 1Filename = Mypa & col & ".txt" '文件名Open Filename For Output As #1For rr = i To i + 4If rr > Myr Then Data = "" & vbTab & "" & vbTab & n: Print #1, (Data): Exit ForIf rr <> i + 4 ThenData = Arr(rr, 1) & vbTab & Arr(rr, 2) & vbTab & Arr(rr, 3)n = n + Arr(rr, 3)ElseData = "" & vbTab & "" & vbTab & nEnd IfPrint #1, (Data)NextClose #1NextApplication.ScreenUpdating = TrueEnd Sub13,导入文本文件(用文本文件名为新表命名)Sub Drwbwj()' 导入文本文件,用文本文件名为新表命名‘导入文本文件.xls (自编宏之一)' by:蓝桥玄霜' 2007-3-7‘/dispbbs.asp?boardid=5&id=13592Dim Mystr As StringDim filename '文件路径'选取文件Application.ScreenUpdating = FalseOn Error GoTo 100Dofilename = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "请选择文件", , MultiSelect:=False)ActiveWorkbook.Worksheets.Add '把文本文件导入Excel新表"TEXT;" & filename, Destination:=Range("A1")).Refresh BackgroundQuery:=FalseEnd With[j2] = filename '以下为获取文件名,给新表命名[j3].SelectActiveCell.FormulaR1C1 = _"=RIGHT(R[-1]C,LEN(R[-1]C)-FIND(""/"",SUBSTITUTE(R[-1]C,""\"",""/"",LEN(R[-1]C)-LEN (SUBSTITUTE(R[-1]C,""\"","""")))))"[j4].SelectActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,LEN(R[-1]C)-4)"Mystr = [j4]'MsgBox Mystr = MystrRange("j2:j4").ClearContents '删除辅助列Loop Until filename = FalseGoTo 200100:Application.DisplayAlerts = False ‘不使报警ActiveWindow.SelectedSheets.DeleteApplication.DisplayAlerts = True200:Application.ScreenUpdating = TrueEnd SubSub LxDrwbwj()' 连续导入文本文件‘导入后.xls' by:蓝桥玄霜' 2007-3-19Dim filename ‘文件路径Dim Myr1%, n%Application.ScreenUpdating = FalseOn Error GoTo 200ActiveWorkbook.Worksheets("Sheet1").Activate '激活表1n = 1Dofilename = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "请选取文件", , MultiSelect:=False) ‘选取文本文件"TEXT;" & filename, Destination:=Range("A" & n)).Refresh BackgroundQuery:=FalseIf n > 1 ThenRange("a" & n).EntireRow.Delete ‘第二个表头行删除End IfMyr1 = [a1].End(xlDown).Rown = Myr1 + 1End WithLoop Until filename = False200:Application.ScreenUpdating = TrueEnd Sub14,导出到文本文件‘2007314‘体彩3D分析.xls (自编宏之一)‘先选择要导出的数据Private Sub CommandButton1_Click()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j As IntegerDim Data As StringDim cell As RangeSet cell = Selection ‘选择数据cols = cell.Columns.Countrows = cell.rows.CountFilename = "G:\Excel论坛\精英培训\数据0313.txt"Open Filename For Output As #1For i = 1 To rowsData = cell.Cells(i, cols) ‘一列数据If IsEmpty(cell.Cells(i, cols)) Then Data = ""Print #1, (Data) ‘字符串型可去除””‘如果用Write #1 Data,输出的是”200365”Next iClose #1End Sub15,导出指定区域数据到文本文件,路径可选择(GetSaveAsFilename)‘/dispbbs.asp?boardID=2&ID=316431&page=1&px=0Private Sub CommandButton1_Click()Dim Filename As StringDim rows As Long, cols As IntegerDim i As Long, j%Dim Data As StringDim cell As RangeSet cell = Selection '选择数据cols = cell.Columns.Countrows = cell.rows.Count‘Filename = Application.GetSaveAsFilename("Text files (*.txt),*.txt")DoFilename = Application.GetSaveAsFilenameLoop Until Filename <> FalseOpen Filename For Output As #1For i = 1 To rowsFor j = 1 To colsData = cell.Cells(i, j) & " "If j = cols Then Print #1, (Data): GoTo 100Print #1, (Data);Next j100:Next iClose #1End Sub16,导入指定文件夹的文本文件(包括子文件夹),用文本文件名为新表命名,FileSearch,分列Sub pldrwb0423()‘inandout.xls EP'批量导入指定文件夹文本文件Dim myFs As FileSearchDim myPath As String, Filename$Dim i As Long, n As LongSet myFs = Application.FileSearchmyPath = ThisWorkbook.Path & "\source\" '你的文本文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypeNoteItem.Filename = "*.txt".SearchSubFolders = True '同时也搜索子文件夹If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)Filename = myfile(i)aa = InStrRev(Filename, "\")nm = Right(Filename, Len(Filename) - aa)nm = Left(nm, Len(nm) - 4)ActiveWorkbook.Worksheets.Add '把文本文件导入Excel新表With ActiveSheet.QueryTables.Add(Connection:= _"TEXT;" & Filename, Destination:=Range("A1")).Refresh BackgroundQuery:=FalseEnd With = nmColumns("A:A").SelectSelection.TextToColumns Destination:=Range("A1"), Space:=True, FieldInfo _:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True[a1].SelectNextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = NothingEnd Sub17,批量删除同文件夹里指定工作簿文件,‘/dispbbs.asp?boardid=5&id=87719&star=1#1101674Sub plsc0119()'批量删除指定的文件Dim myFs As FileSearchDim myPath As String, Filename$Dim i As Long, n As Long, myFileSet myFs = Application.FileSearchmyPath = ThisWorkbook.Path '你的文本文件夹With myFs.NewSearch.LookIn = myPath.FileType = msoFileTypeNoteItem.Filename = "*.xls"If .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountReDim myFile(1 To n) As StringFor i = 1 To nmyFile(i) = .FoundFiles(i)If InStr(myFile(i), "一月") > 0 Or InStr(myFile(i), "二月") > 0 Or InStr(myFile(i), "三月") > 0 ThenKill myFile(i)End IfNextEnd IfEnd WithEnd Sub18,统计文件夹里子文件夹名及所有的文件名‘/viewthread.php?tid=393673&page=1&extra=page%3D1‘示例.rarSub wjjm()'文件夹名Dim fso, f, fc, myPath$, i%, myFolSet fso = CreateObject("Scripting.FileSystemObject")myPath = ThisWorkbook.pathSet f = fso.GetFolder(myPath)Set fc = f.SubFoldersFor Each myFol In fci = i + 1Cells(i, 1) = NextSet fso = NothingEnd SubSub wjjm()'同目录下文件名(Files对象)Dim fso, f, fc, myPath$, i%, myFolSet fso = CreateObject("Scripting.FileSystemObject")myPath = ThisWorkbook.PathSet f = fso.GetFolder(myPath)Set fc = f.FilesFor Each myFol In fcIf Right(, 3) = "xls" Theni = i + 1Cells(i, 1) = End IfNextSet fso = NothingEnd Sub19,对文件夹里没有后缀名的文件加”.txt”后缀‘2009-5-4 EPSub tjwjjwj()'统计文件夹文件Dim myFs As FileSearchDim myPath As StringDim i As Long, n As LongSet myFs = Application.FileSearchmyPath = ThisWorkbook.pathWith myFs.NewSearch.LookIn = myPath.SearchSubFolders = TrueIf .Execute(SortBy:=msoSortByFileName) > 0 Thenn = .FoundFiles.CountMsgBox "该文件夹里有" & n & "个文件"ReDim myfile(1 To n) As StringFor i = 1 To nmyfile(i) = .FoundFiles(i)aa = InStrRev(myfile(i), "\")nm = Right(Myfile(i), Len(Myfile(i)) - aa)‘nm = Left(nm, Len(nm) - 4)Cells(i, 1) = nmNextElseMsgBox "该文件夹里没有任何文件"End IfEnd WithSet myFs = Nothing。

相关文档
最新文档