excel 捕获数组中的值并在另一个工作表中返回值

afdcj2ne  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(108)

我想从Excel中的标记工作表中捕获数组中的值,并在下一个工作表中返回值。我试图使数组动态化。我编写的代码如下:

Private Sub CommandButton1_Click()

Dim myarr() As String

Dim lrow As Integer, lc As Integer, r As Integer, c As Integer
lrow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
lc = Sheets("Sheet1").Range("A1").End(xlToRight).Column

ReDim myarr(lrow, lc) As String
For r = 1 To lrow
    For c = 1 To lc
        myarr(r, c) = Cells(r, c).Value
    Next c
Next r

Sheets("Sheet2").Select

For r = 1 To lrow
    For c = 1 To lc
        Cells(r, c) = myarr(r, c)
    Next c
Next r

End Sub

我期望数组返回表2中的值,但没有得到结果。它没有发出错误。

bvuwiixz

bvuwiixz1#

在可能的情况下,用特定的工作表引用限定范围,不要依赖Select。我希望在运行代码时选择了工作表2,因此第一个Cells(r, c).Value将引用该工作表。

Option Explicit
Private Sub CommandButton1_Click()

    Dim ws1 As Worksheet, ws2 As Worksheet, wb As Workbook
    Dim myarr() As String
    Dim lrow As Integer, lc As Integer, r As Integer, c As Integer
    
    Set wb = ThisWorkbook
    Set ws1 = wb.Sheets("Sheet1")
    Set ws2 = wb.Sheets("Sheet2")
    
    lrow = ws1.Range("A" & Rows.Count).End(xlUp).Row
    lc = ws1.Range("A1").End(xlToRight).Column
    
    ReDim myarr(lrow, lc) As String
    For r = 1 To lrow
        For c = 1 To lc
            myarr(r, c) = ws1.Cells(r, c).Value
        Next c
    Next r
    
    For r = 1 To lrow
        For c = 1 To lc
            ws2.Cells(r, c) = myarr(r, c)
        Next c
    Next r

End Sub

或者更简单地说

Private Sub CommandButton1_Click1()

    Dim myarr
    With ThisWorkbook
       myarr = .Sheets("Sheet1").UsedRange
       .Sheets("Sheet2").Range("A1").Resize(UBound(myarr), UBound(myarr, 2)) = myarr
    End With

End Sub

相关问题