-1

一些上下文: - 我正在构建一个大表(1000x1000) - 我想用值 1 填充一些案例 - 我将每个案例的行和列放在单独的表中

这是我用来填写表格的代码。如您所见,我在 For 循环中使用 Range。它以前使用较小的数据集。造成麻烦的行是这一行: Sheets("Feuil1.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"

Sub FillEdges()
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A53498")
    Sheets("Feuil1.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"    
Next rng
End Sub

做一些研究后,我了解到我可能想偶尔保存、关闭和重新打开工作簿。我试过了,但似乎 VBA 没有考虑“保存、关闭和重新打开”代码。我试图通过这个帮助页面找出一些东西:

http://support.microsoft.com/kb/210684/en-us

这导致我使用此代码出现错误 91。错误在第三行。

    Sub FillEdges()
        Dim rng As Range, mybook As Workbook

mybook.SaveAs "Macintosh HD:Users:Nicolas:test.xslm", FileFormat:=53
    For Each rng In Sheets("Feuil2").Range("A1:A53498")
    If rng Mod 2500 = 0 Then
                mybook.Close SaveChanges:=True
                Set mybook = Nothing
                Set mybook = Application.Workbooks.Open("Macintosh HD:Users:Nicolas:test.xslm")
            End If
        Sheets("Feuil1.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"

    Next rng
    End Sub

您知道如何解决此错误 91 吗?

所以我不确定这是否会完全修复错误 1004,但我认为这是正确的路径。或者,也许你会建议别的东西......?

非常感谢您的时间。祝你有美好的一天。尼古拉斯。

4

1 回答 1

0

这就是我最终的做法。在编码之前了解有关 VBA 的更多信息是这里的关键!特别是关于打开、保存和关闭文件。

请注意,最后我几乎没有触及我上面引用的微软网站的例子。

Sub remplir()

Application.ScreenUpdating = False

Dim rng As Range
Dim worksheet1 As Worksheet

Dim iTemp As Integer
Dim oBook As Workbook
Dim iCounter As Long


Set worksheet1 = ActiveWorkbook.ActiveSheet
iCounter = 1

    ' Open the new full of zeros workbook:

    Application.Workbooks.Open "Macintosh HD:Users:Nicolas:vba:test.xlsm"
    Set oBook = ActiveWorkbook



    'iTemp = Application.SheetsInNewWorkbook
    'Application.SheetsInNewWorkbook = 1
    'Set oBook = Application.Workbooks.Add
    'Application.SheetsInNewWorkbook = iTemp

    ' Add a defined name to the workbook
    ' that RefersTo a range:
    oBook.Names.Add Name:="tempRange", _
        RefersTo:="=Sheet1!$A$1"

    ' Save the workbook: (attention extension fausse, mais ça n'empeche rien !)
    oBook.SaveAs "Macintosh HD:Users:Nicolas:vba:test.xslm", FileFormat:=53

    ' Work the sheet in a loop. Eventually,
    ' you get error 1004: Copy Method of
    ' Worksheet class failed.
  For Each rng In worksheet1.Range("A1:A5038")

  If rng.Value > 0 And rng.Row <> 1 Then
  If rng.Value <> rng.Offset(-1, 0).Value Then
  iCounter = iCounter + 1
  End If
  End If

    Sheets("Feuil1").Cells(iCounter, rng.Offset(0, 1).Value + 1) = "1"
    Sheets("Feuil1").Cells(iCounter, 1) = rng.Value
        'Uncomment this code for the workaround:
        'Save, close, and reopen after every 100 iterations:
        If rng Mod 1000 = 0 Then
            oBook.Close SaveChanges:=True
            Set oBook = Nothing
            '(attention extension fausse, mais ça n'empeche rien !)
            Set oBook = Application.Workbooks.Open("Macintosh HD:Users:Nicolas:vba:test.xslm")
        End If

Next rng
于 2013-03-20T04:11:21.767 回答