在excel列表中写入并将字符串替换为txt文件

时间:2018-05-21 13:13:05

标签: excel vba excel-vba text

如果有人能指出我正确的方法来实现这一点,我将非常感激。

我有一张excel牌桌,是一个小联盟垒球队的击球手名单。我想将每个名称写入一个txt文件,一次一个,因为他们来蝙蝠,并替换前一个。 txt文件的内容将叠加到视频流上。因此每次女孩出现时,我都想做一些简单的事情,这样可以将excel表中的下一行写入文本文件中,取代之前的文本。

谢谢!

2 个答案:

答案 0 :(得分:0)

你可以这样做,它会将与预定范围重叠的(第一个)所选单元格的值输出到指定的文本文件。

这是由选择更改触发的,因此每当选择一个新的(匹配的)单元格时,都会输出一个新文件 - 因此代码应该放在相应的工作表模块中:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim r As Range
    Dim rFind As Range
    Dim sTxt As String
    Dim sPath As String

    'Change path / name for text file output
    sPath = "C:\Temp\XLText.txt"

    'Change to range continaing the list of values to select / output
    Set rFind = Sheet1.ListObjects(1).ListColumns("Column1").DataBodyRange

    Set r = Intersect(Target, rFind)
    If Not r Is Nothing Then
        sTxt = r.Cells(1).Value
       WriteTextFile sTxt, sPath
    End If

End Sub


Sub WriteTextFile(ByVal s As String, ByVal sPath As String)
    Dim fso As Object
    Dim oFi As Object

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFi = fso.CreateTextFile(sPath)

    oFi.WriteLine s
    oFi.Close

    Set fso = Nothing
    Set oFi = Nothing
End Sub

答案 1 :(得分:0)

此设置会自动更改为下一个击球手,并在阵容开始时重置。点击每个新击球手的按钮。

Sub saveAsTxt()

    Dim ws As Worksheet
        Set ws = Sheets("Sheet1")

    Dim wsTwo As Worksheet
        Set wsTwo = Sheets("Sheet2")

    Dim NextBatterCounter As String
        NextBatterCounter = ws.Range("C4")

    Dim filePath As String
        filePath = "Z:\New folder\"

    Dim fileName As String
        fileName = "BatterUp"

    ' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
    ' the FileSystemObject which has many useful features for handling files and folders

    Dim fso As New FileSystemObject
    Dim fileStream As TextStream

    Set fileStream = fso.CreateTextFile(filePath & fileName)

    fileStream.WriteLine ws.Range("A" & NextBatterCounter)

    fileStream.Close

    If ws.Range("C4") < 16 Then
        ws.Range("C4") = ws.Range("C4") + 1
    Else
        ws.Range("C4") = 2
    End If

End Sub