首页 > 解决方案 > VBA Excel: how to use a variable for the file number used for open, print and close

问题描述

I would like to use a variable for the file number, instead of hard-coding it.

I have tried with conversions like CDbl to have a double, as it seems that #1 means convert 1 into double.. But this did not work. It also does not work without conversion, so until now, using #1 (or any number) is the only way to interact with a file that worked fine.

Open f_output For Append As #2
Print #2, "hello"
Close #2

I would like it to look like

dim fileNumber as double
fileNumber = 2
Open f_output For Append As fileNumber
Print fileNumber, "hello"
Close fileNumber

标签: excelvba

解决方案


Here is the answer I was looking for.

dim fileNum
fileNum = 3

Open f_output For Append As #fileNum
Print #fileNum, s
Close #fileNum

Additionally, the built-in function FreeFile can be used to get a free file number.

fileNum = FreeFile

推荐阅读