【发布时间】:2020-09-04 21:01:05
【问题描述】:
我对此比较陌生,但我能够编写我的第一个代码,它实际上完成了一些有用的事情。该代码的目的是打开一个电子表格,从名称给定的行中提取值并将其复制到主电子表格等中。
不幸的是,当单元格中的间距发生变化时,代码并不是特别健壮。有没有办法将此“总运营费用”更改为如下所示:“*总运营费用*”,目的是间距不重要,只有单元格中的单词重要
If Cells(i, 1).Value = " Total Operating Expenses" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 9 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
整个代码如下:
Sub ImportData()
Dim filePath As String
Dim SourceWb As Workbook
Dim TargetWb As Workbook
Dim Cell As Range
Dim i As Integer
Dim k As Integer
Dim Lastrow As Long
Dim Lastrow2 As Long
'SourceWb - Workbook were data is copied from
'TargetWb - Workbook were data is copied to and links are stored
Application.ScreenUpdating = False
Set TargetWb = Application.Workbooks("APC Refi Tracker.xlsm")
Lastrow = Range("E100").End(xlUp).Row - 6
For k = 1 To Lastrow
filePath = TargetWb.Sheets("Import").Range("E" & 6 + k).Value
Set SourceWb = Workbooks.Open(filePath)
On Error Resume Next
Lastrow2 = Range("A500").End(xlUp).Row - 2
For i = 1 To Lastrow2
If Cells(i, 1).Value = " Total Rental Income" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 4 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
If Cells(i, 1).Value = " Total Other Income" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 5 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
If Cells(i, 1).Value = " Total Operating Expenses" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 9 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
Next
SourceWb.Close
Next
Application.ScreenUpdating = True
Worksheets("Import").Activate
MsgBox "All done!"
End Sub
【问题讨论】: