'
代码清单15.5: 一个使用WRITE#和INPUT#的例子
Sub
TestWriteInput()
WriteExample
InputExample
End Sub
'
Creates a comma-delimited file based
'
on a range in Excel that is 8
'
columns wide
Sub
WriteExample()
Dim
lOutputFile
As
Long
Dim
rg
As
Range
'
Set rg to refer to upper-left cell of range
Set
rg
=
ThisWorkbook.Worksheets(
1
).Range(
"
A1
"
)
'
Get a valid file number
lOutputFile
=
FreeFile
'
Create a new file for output
Open
"
C:\Write Example.txt
"
For
Output
As
#lOutputFile
'
Loop until there isn't any data in the first column
Do
Until
IsEmpty(rg)
'
Write the data to the file
Write
#lOutputFile, rg.Value, _
rg.Offset(
0
,
1
).Value, _
rg.Offset(
0
,
2
).Value, _
rg.Offset(
0
,
3
).Value, _
rg.Offset(
0
,
4
).Value, _
rg.Offset(
0
,
5
).Value, _
rg.Offset(
0
,
6
).Value, _
rg.Offset(
0
,
7
).Value
'
Move down to next row
Set
rg
=
rg.Offset(
1
,
0
)
Loop
Set
rg
=
Nothing
Close lOutputFile
End Sub
Sub
InputExample()
Dim
lInputFile
As
Long
Dim
rg
As
Range
'
variant variables for reading
'
from text file
Dim
v1, v2, v3, v4
Dim
v5, v6, v7, v8
'
set rg to refer to upper-left cell of range
Set
rg
=
ThisWorkbook.Worksheets(
2
).Range(
"
a1
"
)
'
clear any existing data
rg.CurrentRegion.ClearContents
'
Get a valid file number
lInputFile
=
FreeFile
'
create a new file for input
Open
"
C:\Input Example.txt
"
For
Input
As
#lInputFile
'
loop until you hit the end of file
Do
Until
EOF
(lInputFile)
'
Read the data to the file
'
have to read into a variable - an't assign
'
directly to a range
Input
#lInputFile, v1, v2, v3, v4, v5, v6, v7, v8
'
Transfer values to that worksheet
rg.Value
=
v1
rg.Offset(
0
,
1
).Value
=
v2
rg.Offset(
0
,
2
).Value
=
v3
rg.Offset(
0
,
3
).Value
=
v4
rg.Offset(
0
,
4
).Value
=
v5
rg.Offset(
0
,
5
).Value
=
v6
rg.Offset(
0
,
6
).Value
=
v7
rg.Offset(
0
,
7
).Value
=
v8
'
move down to next row
Set
rg
=
rg.Offset(
1
,
0
)
Loop
Set
rg
=
Nothing
Close lInputFile
End Sub