【发布时间】:2020-11-11 16:07:15
【问题描述】:
我想运行一个宏:在一个单元格中插入来自另一个单元格的信息,然后运行一个宏将该工作表转换为 PDF。我有一种方法可以使用多个 if-then 语句,但我想知道是否有更清洁、更简单的方法。下面是我的代码。单元格的数量可能会有所不同,因为它基于另一个将信息放入其中的宏。下面是代码。
Sub sub1()
Dim ws, ws1, ws2 As Worksheet
Dim LastRow As Long
Set ws = Worksheets("sht1")
Set ws1 = Worksheets("sht2")
Set ws2 = Worksheets("sht3")
LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
With ws1
.Cells.ClearContents
End With
With ws
.AutoFilterMode = False
.Range("A1:T" & LastRow).AutoFilter Field:=7, Criteria1:="=" & Date
End With
ws.Columns(1).Copy Destination:=ws1.Columns(1)
With ws
.AutoFilterMode = False
End With
If ws1.Range("A2").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A2").Value
Call PDFCreate
Else
End If
If ws1.Range("A3").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A3").Value
Call PDFCreate
Else
End If
If ws1.Range("A4").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A4").Value
Call PDFCreate
Else
End If
If ws1.Range("A5").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A5").Value
Call PDFCreate
Else
End If
If ws1.Range("A6").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A6").Value
Call PDFCreate
Else
End If
If ws1.Range("A7").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A7").Value
Call PDFCreate
Else
End If
If ws1.Range("A8").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A8").Value
Call PDFCreate
Else
End If
If ws1.Range("A9").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A9").Value
Call PDFCreate
Else
End If
If ws1.Range("A10").Value <> "" Then
ws2.Range("D13").ClearContents
ws2.Range("D13").Value = ws1.Range("A10").Value
Call PDFCreate
Else
End If
ws2.Range("D13").ClearContents
结束子
【问题讨论】:
-
听起来你需要一个循环。只需找到
ws1上的最后一行,然后循环For Each cell in ws1.Range("A2:A" & lastRow)。 -
@BigBen 我不熟悉循环。试过这个,但它对每个单元格都不起作用 ws1.Range("A2:A" & nRows) ws2.Range("D13").ClearContents ws2.Range("D13").cell.Value Next cell跨度>
-
网上有很多关于如何循环的教程。你试过阅读吗?这是学习基本技能的绝佳机会。