【发布时间】:2021-09-29 03:48:15
【问题描述】:
我有一系列电子表格,我们使用这些电子表格将参数加载到数据库中,以实现点击式订单输入。一些电子表格有数百张工作表,保持最新状态一直是个问题。我要做的是插入一些代码,这些代码将逐页进行,并将每个选项卡中的一些数据编译到摘要表中。
我已经修改了来自Excel VBA to insert sheet name on each row when combining data tables with variable columns 的代码,但我是个彻头彻尾的黑客,到目前为止还没有成功。
简而言之,我需要代码来返回 A 列中的工作表名称,然后扫描第一行以查找第一个未使用的列,然后将该列的内容返回到 C 列和它来自的行#汇总表上的 B 列。
此示例说明了数据的结构,一系列问题,最后有答案。它们不是静态的,但问题在第 1 行有标题(有时只是一个空格值),但答案没有,该列的单元格 1 始终为空白(null)。
编辑:使用 Stack Overflow 上的多个资源,我设法将它拼凑在一起,几乎可以正常工作。我需要找到带有空标题的第一列(第 1 行)和任何中断之前的最后一行,而不是找到最后使用的列和行。这是因为在数据右侧和可能下方的大多数工作表中添加了注释。
Sub CopyData()
Application.ScreenUpdating = False
Dim wsSummary As Worksheet
Dim LastRowWs As Long
Dim LastColWs As Long
Dim LastRowSummary As Long
Dim StartRowSummary As Long
Set wsSummary = ThisWorkbook.Worksheets("Summary") ' defines WsSummary
LastRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row + 1 ' identifys the last used row on target summary sheet
wsSummary.Range("A2:ZZ" & LastRowSummary).Clear 'clears a set range on target summary sheet
For Each Ws In ThisWorkbook.Worksheets
Select Case Ws.Name
Case "Summary", "Category", "TOC", "Index"
'If it's one of these sheets, do nothing
Case Else
LastRowWs = Ws.Cells(Ws.Rows.Count, "A").End(xlUp).Row ' Finds the last column in worksheet
LastColWs = Ws.Cells(LastRowWs, Columns.Count).End(xlToLeft).Column ' Finds the last used colun in Worksheet - ISSUE, I need first null cell column!
StartRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row + 1 'first empty row
Ws.Range(Split(Cells(, LastColWs).Address, "$")(1) & "2:" & Split(Cells(, LastColWs).Address, "$")(1) & LastRowWs).Copy Destination:=wsSummary.Range("A" & StartRowSummary)
LastRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row
wsSummary.Range("B" & StartRowSummary & ":B" & LastRowSummary) = Ws.Name ' returns sheet name
wsSummary.Range("C" & StartRowSummary & ":C" & LastRowSummary) = LastColWs 'returns column #
wsSummary.Range("D" & StartRowSummary & ":D" & LastRowSummary) = Split(Cells(, LastColWs).Address, "$")(1) 'returns Column letter
End Select
Next
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
请告诉我们你自己尝试了什么。 How to ask.
-
我将编辑我的原始帖子。
-
您的代码与您要做什么的描述不符?例如。 ColB 与 ColA 中的工作表名称,源 Row# 与源 Col#... 通常,“行”和“列”之间存在很多混淆,因此很难理解。