繁体   English   中英

用于读取 xls 和操作单元格的 VBA 脚本代码

[英]VBA Script Code for reading a xls and manipulating cells

我有一张只有一张工作表的 Excel 工作表。 此 Excel 工作表的第一行具有列的标题。

工作表在下面的列和 n 行中有数据:

列:A | 乙 | C | D | E | F | G | H

  1. 首先,我正在创建文件的副本并重命名它 - 这有效!

     'Copy and rename the file Dim sourceFile As String, destFile As String sourcePath = Range("D6") destFile = Split(sourcePath, ".")(0) + "_Formated.xls" FileCopy sourcePath, destFile
  2. 我想通过 VBA 代码阅读这个 destFile excel 表。 我将进行一些单元格操作,因此请给我一个工作代码,以了解如何读取整个工作表以及如何在 for 循环中访问特定行。

  3. 我还想知道通过 VBA 代码向这个 destFile excel 表添加新列标题和值的代码。

  4. 仅通过 VBA 代码清除单元格值而不删除单元格的代码是什么。

  1. 我想通过 VBA 代码阅读这个 destFile excel 表。 我将进行一些单元格操作,因此请给我一个工作代码,以了解如何读取整个工作表以及如何在 for 循环中访问特定行。
dim sh as Worksheet
set sh =  Workbooks.Open(destFile).Worksheets(1)
  1. 我还想知道通过 VBA 代码向这个 destFile excel 表添加新列标题和值的代码。
sh.rows(1).Insert Shift := xlDown
ThisWorkbook.Worksheets(1).Rows(1).Copy sh.Rows(1)
  1. 仅通过 VBA 代码清除单元格值而不删除单元格的代码是什么。
sh.Range("A1").Value = ""

我设法用下面的代码完成了这项工作。 这是最糟糕的编码方式,看起来并不复杂,但它完成了工作。 谢谢!

Sub Format()

'Copy and rename the file
Dim SourceFile As String, DestFile As String
SourceFile = Range("D6")
SourceString = Range("D3")
TestSuiteName = Range("D2") & "\"
DestFile = Split(SourceFile, ".")(0) + "_Formated.xls"
On Error GoTo ErrorHandler:
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FileExists(DestFile) Then
    FileCopy SourceFile, DestFile
End If

'Read DestFile worksheet content
Dim wks As Worksheet
Set wks = Workbooks.Open(DestFile).Worksheets(1)

Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long

LastRow = wks.Cells(wks.rows.Count, "A").End(xlUp).Row

For i = 2 To LastRow
    If Cells(i, 6).Value = "Step 1" Then
        Cells(i, 7) = "Other_Migration_Fields" & Cells(i, 7) & vbLf & vbLf & "QC Path:" & Cells(i, 8)
        Cells(i, 8) = Replace(Cells(i, 8), SourceString, TestSuiteName)
    Else
        Cells(i, 1) = ""
        Cells(i, 2) = ""
        Cells(i, 7) = ""
        Cells(i, 8) = ""
    End If
Next i

ErrorHandler:
    Msg = "Error # " & Str(Err.Number) & " was generated by " & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
    If Err.Number <> 0 Then
        MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
    Else
        MsgBox "Success!"
    End If
    Exit Sub

End Sub

暂无
暂无

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

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