使用VBA,无法将单元格值存储在变量中并抛出1004错误

时间:2018-03-21 20:33:45

标签: excel vba excel-vba excel-formula

我正在学习vba阶段。我试图在变量中存储一个值,但不能使用Cell和Range,它会抛出1004错误

以下是我的代码

Sub myself()

Dim str As String
Dim rock As String
Dim MaxStrLen As Integer
Dim StrLen As String
Dim LastRow As Long
Dim LastCol As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim i As Integer
Dim j As Integer

Dim FilePath As String

Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")

LastRow = Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

Open "C:\Users\Antony\Desktop\test.txt" For Output As #2

ws1.Activate

With ws1
For i = 0 To LastRow
For j = 0 To LastCol

.Range(.Cells(i,j))。Value = str

Next j

Next i

Print #2, str
End With

Close #2

End Sub

突出显示的行是1004错误。请帮助解决并在记事本中存储变量。

提前致谢!

1 个答案:

答案 0 :(得分:2)

只需使用

.Cells(i, j).Value = str

顺便说一句,你最好明确地将你的范围引用限定为worksheet对象(如果涉及多个工作簿,则直到workbook对象),否则它将隐式假设{{1 (和ActiveWorkbook)

所以,而不是

ActiveSheet

使用

LastRow= Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

LastRow= ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row
LastCol = ws1.Cells(1, ws1.Columns.Count).End(xlToLeft).Column

所以你的代码可以重构如下:

With ws1
    LastRow= .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With