2017-05-04 74 views
1

通过Excel VBA宏,我试图在excel中打印最多10个空格分隔的参数。例如,我有我的选择范围内的24个值A1:A24 - (说Val1,Val2,Val3,Val4等) 使用下面的VBA代码,我想要输出在“outfile蝙蝠 “作为Excel VBA额外换行通过打印语句插入

”C:\ Program Files文件(x86)的\谷歌\镀铬\应用\的chrome.exe“ VAL1 VAL2 .... Val10

” C:\ Program Files文件(x86)的\谷歌\ Chrome \ Application \ chrome.exe“Val11 Val2 .... Val20

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

即每行最多应打印10个参数值(用空格分隔)。任何高于应该移动到下一行(再次的10空间分隔参​​数最大值)

不知何故,下面的代码是 (1)NOT输出保持到同一线路和 (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 

请让我知道这可能是走错了。 由于

+1

快速测试,试试'打印#7,“”“C:\ ProgramFiles \ ... \ chrome.exe”“”'? (换句话说,使用双引号打印报价而不是'CHR()') – BruceWayne

+0

感谢您输入@BruceWayne。这包括在DavidZemens的回答中。感谢你的帮助! – user6337701

回答

1

打印语句打印线到文件中,在端部因此增加vbNewLine的每个是多余的。您还在为每个参数值(您的代码中的cellValue)拨打Print,这就是为什么这些参数都出现在自己的产品线上的原因。

您可能最有可能将整个整个文件内容作为单个字符串构建,然后使用单个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 

我们得到以下的输出:

enter image description here

+0

非常感谢@DavidZemens。奇迹般有效! +1,并将其标记为答案! – user6337701