简体   繁体   中英

Compile error on assignment to array — VBA (Excel)

I want to assign values to an Integer array, but instead I got a compile-time error.

Here is my code:

Private Sub A()
    Dim i As Integer
    Dim Width(3) As Integer
    Dim TempArray As Variant
    TempArray = Array(12, 6, 12, 5)
    For i = 0 To 3
        Width (i) = CInt(TempArray(i))
    Next i
End Sub

The error is on this line:

Width (i) = CInt(TempArray(i))

The error message is: "Compile Error. Expected:#".

I don't know what's wrong with this statement. Did I use a reserved word? I am new to VB, but I do need help. Thanks in advance.

Your comment led me to a little more research. Width isn't just an Excel reserved word, as in Column.Width . It's actually a VBA statement having to do with writing to text files, and it expects the number of a file opened for output.

Here's the text from Excel 2010 VBA help:

Width # Statement

Assigns an output line width to a file opened using the Open statement.

Syntax

Width #filenumber, width

The Width # statement syntax has these parts:

Part Description filenumber Required. Any valid file number. width Required. Numeric expression in the range 0–255, inclusive, that indicates how many characters appear on a line before a new line is started. If width equals 0, there is no limit to the length of a line. The default value for width is 0.

Example This example uses the Width # statement to set the output line width for a file.

Dim I
Open "TESTFILE" For Output As #1    ' Open file for output.
VBA.Width 1, 5    ' Set output line width to 5.
For I = 0 To 9    ' Loop 10 times.
    Print #1, Chr(48 + I);    ' Prints five characters per line.
Next I
Close #1    ' Close file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM