如何使其适应于其他工作表?

时间:2019-05-03 18:46:55

标签: excel vba

如何使它适应于其他工作表而不是可见的工作表。

If (IsEmpty(Cells(RowNum, ColumnNum).Value)) Then
    GoTo nextloop:
End If

我已经移动了括号,尝试包含工作簿名称,但是我认为我没有得到语法。我对excel不太满意。

我想要实现的目标。取一列的所有内容,将数据推送到bat文件中。脚本将从另一个工作表上的按钮启动。

已更新完整代码 :(尝试Ryan的答案,出现错误。已对其进行了修复,但脚本没有执行任何操作。)

Sub Send2Bat()

    Dim ColumnNum: ColumnNum = 26   ' Column Z - I have the I J and K Columns concatenated there.
    Dim RowNum: RowNum = 0
    Dim objFSO, objFile

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile("C:\Test\Convert.bat")    'Output Path
    aFile = "C:\Test\Convert.bat"


    Dim OutputString: OutputString = ""

    Dim LastRow: LastRow = Application.ActiveSheet.Cells(Application.ActiveSheet.Rows.Count, ColumnNum).End(xlUp).Row

    Do
nextloop:
        RowNum = RowNum + 1
        If (IsEmpty(Cells(RowNum, ColumnNum).Value)) Then
            GoTo nextloop:
        End If
        OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine


    Loop Until RowNum = LastRow

    objFile.Write (OutputString)

    Set objFile = Nothing
    Set objFSO = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

我制作了一个excel工作簿,并在工作表1和工作表2的z列中放入了一些数据。

enter image description here

我调整了您的代码,使其内容如下:

Sub Send2Bat()

Dim ColumnNum: ColumnNum = 26   ' Column Z - I have the I J and K Columns concatenated there.
Dim RowNum: RowNum = 0
Dim objFSO, objFile

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\Test\Convert.bat")    'Output Path
aFile = "C:\Test\Convert.bat"

Dim OutputString: OutputString = ""
Dim targetSheet As Worksheet
Set targetSheet = Application.Worksheets("Sheet1")

Dim LastRow: LastRow = targetSheet.Cells(targetSheet.Rows.Count, ColumnNum).End(xlUp).Row

Do

    RowNum = RowNum + 1

    If Not (IsEmpty(targetSheet.Cells(RowNum, ColumnNum).Value)) Then

        OutputString = OutputString & Replace(targetSheet.Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine

    End If

Loop Until RowNum = LastRow

objFile.Write (OutputString)

Set objFile = Nothing
Set objFSO = Nothing

End Sub

它产生了以下文件:

enter image description here

因此,然后我将targetSheet名称更新为“ Sheet2”

Set targetSheet = Application.Worksheets("Sheet2")

并再次执行。文件已更新为此:

enter image description here

因此,代码至少在基本形式上是好的。在发生这种情况时,您还有其他更新工作表或四处移动的东西吗?