2017-05-04 9 views
1

Excel VBAマクロを使用して、Excelで選択範囲の最大10個のスペース区切り引数を印刷しようとしています。Excel VBA余分な改行が印刷ステートメントを介して挿入される

たとえば、選択範囲A1:A24 - (Val1、Val2、Val3、Val4など)に24の値があります 次のVBAコードを使用して、 "outfile \プログラムファイル(x86の)\ Googleの\クローム\アプリケーションの\ chrome.exe "VAL1 VAL2 .... Val10

"C:\プログラムファイル(x86の)\ GoogleのC"

として" .BAT \ Chrome \ Application \ chrome.exe "Val11 Val2 .... Val20

" C:¥Program Files(x86)¥Google¥Chrome¥Application¥chrome.exe "Val21 Val22 Val23 Val24

つまり、各行は最大10個の引数値(スペースで区切って)で印刷されます。その上何が何らかの形で(再び10空間のmaxは引数を区切っ)次の行に

を移動すべき、次のコードは (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 

これは間違って行くこともどこ私に知らせてください。

おかげ
+1

クイックテストを、 'Print#7、" "" C:\ ProgramFiles \ ... \ chrome.exe "" ''を試してみてください。 (言い換えれば、 'CHR()'の代わりに二重引用符を使用してください) – BruceWayne

+0

@ BruceWayneの入力をありがとう。これはDavidZemensの答えに含まれています。あなたの助けに感謝! – user6337701

答えて

1

印刷ステートメントは、ファイルにラインを印刷するので、各々の端部にvbNewLineを追加することは冗長です。各引数値(cellValue)につき、Printを呼び出しているので、それらのコードがそれぞれの行に表示されています。

ファイルの内容全体を1つの文字列としてに構成した後、単一の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

関連する問題