简体   繁体   English

Excel VBA 将某些数据向下复制 x 行数

[英]Excel VBA Copy certain data down x row count

I am new to VBA, normally i would just resort to excel formulas.我是 VBA 的新手,通常我只会求助于 excel 公式。 I am writing a record database that extracts information from the users chosen excel sheet.我正在编写一个记录数据库,从用户选择的 Excel 表中提取信息。 I have found code over the web that i have bodged together to get this: -我在网上找到了我拼凑起来的代码:-

Sub Get_Data_From_File()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", Filefilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen, Password:="uraduct")
        Application.DisplayAlerts = False
        OpenBook.Sheets(1).Range("B3:B11").Copy
        ThisWorkbook.Worksheets("Data").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues, Transpose:=True
        Application.DisplayAlerts = False
        OpenBook.Sheets(1).Range("B19:U162").Copy
        ThisWorkbook.Worksheets("Data").Cells(Rows.Count, 10).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues, Transpose:=True
        OpenBook.Close False

End If
Application.ScreenUpdating = True
On Error Resume Next
Columns("K").SpecialCells(xlBlanks).EntireRow.Delete

End Sub

Basically, the B3:B11 is a title and i want it to appear on each row that is brought through on the B19:U162 which is either 1 column or 20 columns converted to rows (based on the delete at the end).基本上,B3:B11 是一个标题,我希望它出现在 B19:U162 上的每一行上,它是 1 列或 20 列转换为行(基于最后的删除)。

Also, in some cases the user has not filled in row/column 19 so if row/column 20 is filled i would like to add a default to row 19 to prevent it being overwrote on the next file upload.此外,在某些情况下,用户没有填写第 19 行/列,因此如果第 20 行/列已填​​写,我想为第 19 行添加一个默认值,以防止它在下一个文件上传时被覆盖。

I hope that makes sense.我希望这是有道理的。

Thank you,谢谢,

Test cell("B19") and if empty calculate no of columns from row 20 then fill in the row.测试单元格(“B19”),如果为空,则计算第 20 行的列数,然后填写该行。 Close source workbook without saving changes.关闭源工作簿而不保存更改。

Application.DisplayAlerts = False
Dim cols As Integer
If OpenBook.Sheets(1).Range("B19") = "" Then
    cols = OpenBook.Sheets(1).Cells(20, Columns.Count).End(xlToLeft).Column - 1
    OpenBook.Sheets(1).Range("B19").Resize(1, cols).Value = "empty"
End If
OpenBook.Sheets(1).Range("B19:U162").Copy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM