在满足条件时创build单元格后命名的新文本文件

到目前为止,我看了一下,发现了一些帮助,但是我正在努力为这个Excelmacros创build每个逻辑。

基本上我有4列的数据。 列A具有某种东西的名称,列D具有TRUE或FALSE。

我想要一个macros连接到一个button,在一个给定的目录中创build一个新的文本文件,该目录以列A的内容命名,但是只有该列中的列D被标记为“TRUE”。

例如,如果我有以下。

ColA =testingColD = TRUE

ColA = Test2 ColD = FALSE

ColA = Test3 ColD = TRUE

我将得到两个文本文件主题Test.txt和Test3.txt。

我知道我需要每个循环来查看a1-d的范围(无论数字),然后当D = True做一个SaveAs我猜?

这是我迄今为止的代码(是的,我知道这是非常不完整的,但是就我的逻辑而言,它是在打墙之前得到的)。

Dim fileName As String Dim filePath As String Dim curCell As Object Dim hideRange As Range filePath = "C:\ExcelTest\" hideRange = Range("D1:D1048576") fileName = *Content of Cell A from this Row* For Each Row In Range("A1:D1048576") IF curCell.value In Range hideRange = "TRUE" Then curCell.SaveAs fileName & ".txt, xlTextWindows 

任何帮助,甚至指引我在正确的方向将是伟大的。 我search了一些例子,找不到与我想要做的事情完全匹配的东西。

你很近,但是你正在循环着许多细胞。

这里是循环行的代码,它停在列中最后一个被填充的单元格上。

 Sub LoopRows() dim sht as worksheet set sht = Thisworkbook.Sheets("Name of Worksheet") 'loop from row 1 to the last row containing data For i = 1 To sht.Range("A:A").End(xlDown).Row 'check the value in column 4 for this row (i) If sht.Cells(i, 4).Text = "TRUE" Then CreateFile sht.Cells(i, 1).Value End If Next i End Sub 

为了编写这个文件,为了简单起见,它将引用Microsoft脚本运行时,并按如下所示进行:

 Sub CreateFile(FileName As String) Dim fso As New FileSystemObject fso.CreateTextFile "c:\temp\" & FileName & ".txt", True End Sub 

编辑我看不出为什么你没有得到一个文件创build,我的testing在Windows计算机上工作正常。

你可以请单独在button中尝试下面的代码,看看它是否打开一个文本文件?

 Dim fso As New FileSystemObject fso.CreateTextFile "c:\temp\testfso.txt" Shell "C:\WINDOWS\notepad.exe c:\temp\testfso.txt", vbMaximizedFocus 

编辑2

试试这个,看看它是否打开文本文件..

 Sub CreateFile(FileName As String) Dim fso As New FileSystemObject Dim fName as String fName = "c:\temp\" & FileName & ".txt" fso.CreateTextFile fName, True Shell "C:\WINDOWS\notepad.exe " & fName, vbMaximizedFocus End Sub 

你在找什么是这样的:

 Sub test() Dim filePath As String filePath = "C:\ExcelTest\" Dim xRow As Variant For Each xRow In Range("A1:D100").Rows If xRow(1, 4).Value = "TRUE" Then Open filePath & xRow(1, 1) & ".txt" For Output As #1 Write #1, xRow(1, 2), xRow(1, 3) Close #1 End If Next End Sub 

虽然它的工作没有错误,我不会像现在这样使用它。
如果你有问题,就问吧。

编辑

我已经运行了一些testing,并注意到Windows阻止我在特定的文件夹内创build文件…请试试这个作为一个新的子,并运行它:

 Sub testForText() Open Environ("AppData") & "\Testing.txt" For Output As #1 Write #1, "dada" Close #1 Shell "notepad.exe " & Environ("AppData") & "\Testing.txt", vbNormalFocus End Sub 

然后告诉我,如果记事本打开“Testing.txt”