循环不同表格中的范围(Excel)

时间:2018-06-06 01:53:56

标签: excel vba excel-vba

我有两张:'Project_Name'和'Admin'。

我也有两组数据。我有一个代码试图在两个工作表中循环数据,但它不起作用。

如果循环仅在一张纸上完成,

代码有效,但不能同时在两张纸上完成。我不确定是什么问题?

Dim val1 As String
Dim val2 As String
Dim val3 As String

For i = 1 to LastRow

With Worksheets("Project_Name")
  .Range(i, 1).Value = val1
  .Range(i, 2).Value = val2
End With

With Worksheets("Admin")
  .Range(i, 1).Value = val3
End With

Next i

2 个答案:

答案 0 :(得分:2)

试试这个并调整变量,它对我有用(注意.Range由.Cells重新演绎):

Sub test2()

' Active workbook
Dim wb As Workbook
Set wb = ThisWorkbook
Dim i As Integer

'*******************************************
'Adapt this vars


'define your sheets
Dim ws_pname As Worksheet
Dim ws_admin As Worksheet
Set ws_pname = wb.Sheets("Project_Name")
Set ws_admin = wb.Sheets("Admin")

'define your values
Dim val1 As String
Dim val2 As String
Dim val3 As String

val1 = "test_val1"
val2 = "test_val2"
val3 = "test_val3"

'definie the last Rows
Dim lastRow_pname As Integer
Dim lastRow_admin As Integer

lastRow_pname = ws_pname.Range("A" & Rows.Count).End(xlUp).Row + 1
lastRow_admin = ws_admin.Range("A" & Rows.Count).End(xlUp).Row + 1
'*******************************************

For i = 1 To lastRow_pname


With ws_pname
  .Cells(i, 1).Value = val1
  .Cells(i, 2).Value = val2
End With

Next i

For i = 1 To lastRow_admin
With ws_admin
  .Cells(i, 1).Value = val3
End With
  Next i

End Sub

编辑:以下代码只有一个循环。

Sub test2()

' Active workbook
Dim wb As Workbook
Set wb = ThisWorkbook
Dim i As Integer

'*******************************************
'Adapt this vars


'define your sheets
Dim ws_pname As Worksheet
Dim ws_admin As Worksheet
Set ws_pname = wb.Sheets("Project_Name")
Set ws_admin = wb.Sheets("Admin")

'define your values
Dim val1 As String
Dim val2 As String
Dim val3 As String

val1 = "test_val1"
val2 = "test_val2"
val3 = "test_val3"

'definie the last Rows
Dim lastRow_pname As Long
Dim lastRow_admin As Long
Dim lastRow As Long

lastRow_pname = ws_pname.Range("A" & Rows.Count).End(xlUp).Row + 1
lastRow_admin = ws_admin.Range("A" & Rows.Count).End(xlUp).Row + 1
'*******************************************

'determine biggest last row
If lastRow_pname >= lastRow_admin Then
    lastRow = lastRow_pname
Else
    lastRow = lastRow_admin
End If


For i = 1 To lastRow

    If i <= lastRow_pname Then
      With ws_pname
        .Cells(i, 1).Value = val1
        .Cells(i, 2).Value = val2
      End With
    End If

    If i <= lastRow_admin Then
      With ws_admin
        .Cells(i, 1).Value = val3
      End With
    End If

Next i

End Sub

答案 1 :(得分:1)

10.13.4 似乎错了。循环遍历行/列时首选.Range(i, 2)

Cells(Row,Column)

我的设置在两张纸上都正常工作。