Cannot write to a file using VBA

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

Firstly, I must admit that I have posted this question to the
excel.programming group, but have not yet received a reply. I think the issue
may be related to security so I am hoping for some help in this security
group.

I am trying to run some very simple code to write to a file on my host PC
using an Excel VBA macro:

Sub TestFileOpening()
Dim FileNumber As Integer
FileNumber = FreeFile()
Open "C:\TEST.TXT" For Output As #FileNumber
Write #FileNumber, "This is a sample."
Close #FileNumber
End Sub

The 'write' statement fails with 'Run-time error '54' Bad file mode'. This
means the file was not opened for output.

This code runs fine on a colleague's machine. I have tried setting the Excel
security level to medium or low but still get the error. I am almost certain
the code is correct (as it complies with Microsoft examples) so I suspect a
security issue but I don't know where else to look.

I am running Excel 2003 SP1 on Windows XP Prof SP2.

Is there any Windows security setting that may be preventing the file write
operation?

David
 
Do you have to create the file before you can open it.
Maybe you need a conditional statement along the lines of if the file exists
then open it otherwise create it first.
 
APR said:
Do you have to create the file before you can open it.
Maybe you need a conditional statement along the lines of if the file exists
then open it otherwise create it first.

Sadly no. It makes no difference whether or not the file exists. I think the
VB Open() method copes with either situation.

The code runs on another PC fine. That is why I think it is a security
issue. The only difference we have identified is that in the working
environment the user is an administrator, whilst he is not in the non-working
environment. Could this make a difference?

David
 
DavidTM said:
Sadly no. It makes no difference whether or not the file exists. I think the
VB Open() method copes with either situation.

The code runs on another PC fine. That is why I think it is a security
issue. The only difference we have identified is that in the working
environment the user is an administrator, whilst he is not in the non-working
environment. Could this make a difference?

David

I'm not an XP expert here but, from a Unix perpective, does the non-admin
user have proper permissions in that directory to create a file? Change the
file to something like:
C:\<whaterver the path is to My Stuff in this profile (in win98 that was
Windows\profile\<user name>) >\test.txt

Just a thought.
 
Hi Larry

Thanks for your reply.

Actually, we eventually found that the real-time anti-virus software running
on my PC was blocking execution of the VB script. Unfortunately, it was
giving no indication of doing so.

David
 
Back
Top