Excel VBA额外换行通过打印语句插入

通过一个Excel VBAmacros,我试图在excel中打印最多10个空格分隔的参数。

例如,我有我的select范围内的24个值A1:A24 – (说Val1,Val2,Val3,Val4等)使用下面的VBA代码,我想获得输出在“outfile.bat”

“C:\ Program Files(x86)\ Google \ Chrome \ Application \ chrome.exe”Val1 Val2 …. Val10

“C:\ Program Files(x86)\ Google \ Chrome \ Application \ chrome.exe”Val11 Val2 …. Val20

“C:\ Program Files(x86)\ Google \ Chrome \ Application \ chrome.exe”Val21 Val22 Val23 Val24

即每行最多应打印10个参数值(用空格分隔)。 以上任何东西都应该移到下一行(最多10个空格分隔的参数)

不知何故,下面的代码是(1)不保留输出到同一行和(2)插入一个换行符在第10个值,但不是在第20,第30和其他值。

它产生以下内容:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val1 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val2 C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val3 

等等….

这是我的代码:

 Private Sub GetChromeFile_Click() Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer, a As Integer myFile = "C:\Users\User1\" & "outfile.bat" Set rng = Selection Open myFile For Output As #7 a = 0 For i = 1 To rng.Rows.Count Print #7, Chr(34) & "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & Chr(34) a = a + 1 cellValue = rng.Cells(i).Value If (a = 10) Then Print #7, " " & cellValue & vbNewLine Else Print #7, " " & cellValue End If Next i Close #7 Range("F5").Value = " Done!" End Sub 

请让我知道这可能会出错。 谢谢

print语句在文件中打印一行 ,所以在每个vbNewLine处添加vbNewLine是多余的。 你也打电话给每个参数值(代码中的cellValuePrint ,这就是为什么这些都出现在自己的路线。

您可能很可能将整个文件内容构build为单个string,然后使用单个Print语句来编写整个文件。 如果您处理大量的数据,则可能需要对其进行细分,但在大多数情况下,这应该可行:

 Option Explicit Sub writebat() Const pathTxt$ = """C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" " Dim lineTxt As String Dim cellValue As String Dim fname As String Dim ff As Long Dim a As Long Dim i As Long Dim rng As Range Set rng = Selection ' Range("A1:A37") fname = "C:\Users\User1\" & "outfile.bat" ' "C:\debug\output.txt" ff = FreeFile() Open fname For Output As #ff lineTxt = pathTxt a = 1 For i = 1 To rng.Rows.Count '## Add the cell value to the string lineTxt = lineTxt & rng.Cells(i).Value & " " If a Mod 10 = 0 Then '## Start a new line with the executable path lineTxt = lineTxt & vbNewLine & pathTxt End If a = a + 1 Next Print #ff, lineTxt Close #ff End Sub 

这产生以下输出:

在这里输入图像说明