【问题标题】:Working with the Columns function - Excel VBA使用列函数 - Excel VBA
【发布时间】:2017-08-12 02:36:30
【问题描述】:

我已经在该网站上搜索了一段时间来寻找这个问题的答案,但还没有运气。我有这段代码,我在其中循环遍历一行数字,并根据当时单元格中的数字,确定我复制并粘贴到工作表的内容。我为此使用 Columns,因为这是使我的代码动态化的唯一方法。它可以工作,但是当我粘贴时,我想粘贴比现在粘贴位置更低的单元格。我想知道 Columns 是否有办法指定要粘贴我的数据的列和位置。

代码:

Dim sh      As Worksheet
Dim rw      As Range
Dim row     As Range
Dim cell    As Range
Dim RowCount As Integer

Set rw = Range("A5:CG5")
Set sh = ActiveSheet

For Each row In rw.Rows
    For Each cell In row.Cells
        Select Case cell.Value
        Case "2"
            ThisWorkbook.Worksheets("Sheet1").Range("E27:E51").Copy Destination:=Sheets("Sheet2").Columns(4)
        End Select
    Next cell
Next row

【问题讨论】:

  • 您可以使用 .Cells (msdn.microsoft.com/en-us/vba/excel-vba/articles/…)。示例:.Cells(row,column) = "Something or/"& Variable (Could be another .Cells) 并使用带有 i=i+1 或循环 For i=first_column To last_column 的 For 循环
  • @danieltakeshi 我可以做这样的事情吗? ThisWorkbook.Worksheets("Sheet1").Range("E27:E51").Copy Range(Cells(i,5),Cells(i,5)
  • 您想将此范围复制到哪些单元格和工作表?你不能这样。这是一个示例:stackoverflow.com/questions/42420280/… 和一个更高级的示例stackoverflow.com/questions/12138624/…
  • @danieltakeshi 是的,例如在我的工作表 1 上,我正在复制的单元格从第 27 行开始,当我将其粘贴到新工作表时,它位于单元格 D1。我希望将其粘贴到 D27,但要动态粘贴,以便稍后对其进行更多更改
  • 第 51 行是最后一行吗?

标签: excel vba


【解决方案1】:

你的问题可以像 Jeeped 说的那样解决,使用Destination:=Sheets("Sheet2").Cells(27, 5)Destination:=Worksheets(2).Range("E27")

由于你想多学一点,我做了一个例子说明:

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-column-property-excel 在链接上解释说.Column:

A 列返回 1,B 列返回 2,以此类推。

.Rows 也是如此

使用 .Cells https://msdn.microsoft.com/pt-br/library/office/ff194567.aspx 所以你可以使用 .Cells(Rows,Columns) 或 .Cells(Index from a Range) 或整个对象:

With Worksheets("Sheet1").Cells.Font 
.Name = "Arial" 
.Size = 8 
End With

举个例子,如果你想把你的电子表格变成动态的:从范围 $E$27 复制到最后一行,并从 Sheet1 的 $E 列中写入内容到 Sheet2 的第 1 行上没有任何内容的最后一列。

    Sub test()
'Declare variables here
Dim sht1, sht2 As Worksheet

'sht1 has the data and sht2 is the output Worksheet, you can change the names

last_row = Worksheets(1).Range("E65536").End(xlUp).Row
last_column = Worksheets(2).Cells(1, sht1.Columns.Count).End(xlToLeft).Column

'Data add
For i = 27 To last_row
'Start from Row 27
    Worksheets(2).Cells(i - 26, last_column + 1) = Worksheets(1).Cells(i, 5)
Next i

MsgBox "Data Updated"
End Sub

还有一个基本动态工作簿示例,其中 i=i+1 和 For 循环 split a single row of data into multiple unique rows into a new sheet to include headers as values and cell contents as values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多