打开工作簿,计算范围并将计数写入另一个工作簿

时间:2017-05-11 06:35:49

标签: excel vba excel-vba

我在Excel工作簿中有一个宏,我正在从不同的文件执行计数操作,并在具有宏的文件中更新它。

Private Sub count_Click()
    Dim MyCount(1 To 3) As Long
    Dim myData As Workbook
    Dim Rng As Range

    Set myData = Workbooks.Open("C:\Users\xyz\Desktop\cas\Book3.xlsx") ' selecting a workbook'

    With myData.Worksheets("sheet1")
        Set Rng = Intersect(.Columns(1), .UsedRange)
        MyCount(1) = WorksheetFunction.CountA(Rng)
    End With

    With myData.Worksheets("sheet1")
        Set Rng = Intersect(.Columns(5), .UsedRange)
        MyCount(2) = WorksheetFunction.CountA(Rng)
    End With

    'MsgBox "count is " & MyCount(1)
    Set myData = Workbooks.Open("C:\Users\xyz\Desktop\cas\Book2.xlsm")
       ' the workbook where I want the values to be transferred'

    With myData.Worksheets("sheet1").Range("a1")
        .Offset(RowCount, 0) = MyCount(1)
    End With

    With myData.Worksheets("sheet1").Range("a2")
        .Offset(RowCount, 0) = MyCount(2)
    End With
End Sub

我尝试打开工作簿并更新值,但不显示值。 可能是因为工作簿的实例是打开的,无法更新。

1 个答案:

答案 0 :(得分:0)

如果您认为它可能是开放的只读,您可以尝试:

'MsgBox "count is " & MyCount(1)
 Set myData = Workbooks.Open("C:\Users\xyz\Desktop\cas\Book2.xlsm")

 If myData.ReadOnly Then
    MsgBox "File is Read-only"
    exit sub
 Else
    MsgBox "File is not read-only"
 End If