所以,我有两个子程序。
第一个用于导入工作表,第二个用于删除空行,如果某个条件成立的话。
我想将已导入的工作表的名称传递给DeleteBlankCells()
子例程。我认为这是我们设置的Set wsSht = .Sheets(sWSName)
变量。
在第二个子例程中,您可以看到我想要替换的硬编码表值与从导入传入的值。
这是第一个子程序:
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists(sWSName) Then
Set wsSht = .Sheets(sWSName)
wsSht.Copy after:=sThisBk.Sheets("Sheet3")
Else
MsgBox "There is no sheet with name :Raw_Data in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Sheets("Sheet1").Activate
End Sub
Private Function SheetExists(sWSName) As Boolean
Dim ws As Worksheet
On Error Resume Next
sWSName = InputBox("Enter sheet name")
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
,这是第二个子程序:
Sub DeleteBlankCells()
Dim Rng As Range
Sheets("HARDCODED SHEET NAME").Activate
Set Rng = Rows("1:1").Find(What:="HIVE_FIELD_TYPE", after:=Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
Sheets("HARDCODED SHEET NAME").Columns(Rng.EntireColumn.Address).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
答案 0 :(得分:1)
您可以查看Worksheet
本身,无需使用工作表的名称。
在您的第二个Sub
中,请更改为:
Sub DeleteBlankCells(ws As Worksheet)
Dim Rng As Range
With ws
Set Rng = .Rows("1:1").Find(What:="HIVE_FIELD_TYPE", after:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
.Columns(Rng.EntireColumn.Address).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End With
End Sub
在你的第一个Sub
之后调用它:
Set wsSht = .Sheets(sWSName)
使用:
DeleteBlankCells wsSht
答案 1 :(得分:0)
或者,也许是一个全局变量? (这是完成它的黑客方式)
How to declare Global Variables in Excel VBA to be visible across the Workbook