【问题标题】:Using VBA, Not able to store the cell value in a variable and throws 1004 error使用 VBA,无法将单元格值存储在变量中并引发 1004 错误
【发布时间】:2018-03-21 20:33:44
【问题描述】:

我正处于 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 错误。请帮助解决并存储在记事本中的变量中。

提前致谢!

【问题讨论】:

  • Range 需要两个单元格,一个开始和一个结束。只需使用.Cells(i, j).Value = str
  • 我认为他想要存储在变量str 中的单元格的值,因此需要翻转该赋值的两侧:str = .Cells(i, j).Value
  • 要在循环中单独输出每个单元格值,请在内部 For j 循环中移动 Print 行,否则您只会打印出最后一个值。
  • str = .Cells(i, j).Value 也试过这条线,仍然抛出错误 1004
  • @AntonyPPeter 问题是您的 For 循环从 0 开始。没有第 0 行,也没有第 0 列,这就是导致您的错误的原因。将循环更改为从 1 开始。

标签: vba excel excel-formula


【解决方案1】:

随便用

.Cells(i, j).Value = str

顺便说一句,您最好明确限定您的范围引用到 worksheet 对象(并且,如果涉及多个工作簿,最多到 workbook 对象),否则它会隐式假定 ActiveSheet(和 ActiveWorkbook)

所以,而不是

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

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

Option Explicit

Sub myself()

    Dim str As String
    Dim LastRow As Long
    Dim LastCol As Long
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim i As Long
    Dim j As Long

    Dim FilePath As String

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


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

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

        For i = 1 To LastRow
            For j = 1 To LastCol
                str = .Range(.Cells(i, j)).Value
                Print #2, str
            Next
        Next
    End With

    Close #2

End Sub

【讨论】:

  • 最初我尝试了同样的方法,但它显示了同样的错误。
  • @DisplayName 问题不在于他如何定义结尾,而在于他如何定义开头。来自他的原帖:For i = 0 To LastRow因为没有第0行,所以总会导致1004错误。
  • 但它是正确的语法,那么现在的结果是什么?
  • 你说得对,语法没问题。 OP 只需要让他的 For 循环从实际的行号开始,而不是 0
  • 我使用了这两个选项仍然无法执行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
相关资源
最近更新 更多