excel - 如何在excel中使用vba将不同的单元格值转换为单行?
问题描述
我想将数据从一张纸传输到另一张纸。
- 我的 sheet1 是“表格”类型的工作表。我有命令按钮。
- 按下命令按钮单元格值应复制到另一个 Sheet2。
- 我希望值的每个副本都应该在一行和固定列中。
- 它不应该被覆盖,而是进入下一个空行。
我正在使用以下 VBA 代码:
Private Sub Button1_Click()
Dim rng As Range
Set rng = Sheets("Sheet1").Range("A1,A2,B1,B2,B3")
For Each cell In rng
'here you copy to another sheet, one row lower
Sheets("Sheet2").Cells(cell.Row + 1, cell.Column).Value = cell.Value
Next cell
For x = lRow To 2 Step -1
If Range("I" & x) <> vbNullString Then Range("I" & x).EntireRow.Delete
Next x
Application.CutCopyMode = False
End Sub
解决方案
Option Explicit
Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRow As Long, i As Long
Dim str As String, chara As Variant
Dim rng As Range, cell As Range
With ThisWorkbook
Set ws1 = .Worksheets("Sheet1") '<- Set worksheet ws1
Set ws2 = .Worksheets("Sheet2") '<- Set worksheet ws2
End With
Set rng = ws1.Range("B1:D1,B2:B6,B8:E11") '<- Set the range you want to loop
For Each cell In rng
If str = "" Then '<- Create a string with all details
Else
str = str & "," & cell.Value
End If
Next cell
LastRow = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
i = 1
For Each chara In Split(str, ",") '<- Split with commas
ws2.Cells(LastRow + 1, i) = chara
i = i + 1
Next chara
End Sub
推荐阅读
- php - Cake PHP 2 model query() 删除初始数组项
- ios - 颤振2 fcm ios apn问题
- c++ - 无法将数组转换为包含指针的结构
- android - Room 查询中的“=”和“==”有什么区别?
- orocrm - OroPlatform:具有 GreaterThan 约束 js 验证器的错误时区
- html - 如何使用 css 将文本彼此相邻移动?
- java - Android Studio 通知已实现但未显示
- css - 如何在带有上下文的 Google 登录 (GSI) 按钮上设置响应宽度
- pytorch - 用于 pytorch 中 RNN 的 Nvidia DALI
- c# - 如果 C# 属性像装饰器设计模式一样工作?