我正在处理一个宏,在该宏中,当我按下工作簿中的一个按钮时,代码将在另一工作簿上执行。如果我从唯一的工作簿中执行该命令,则该命令已经起作用,但是我无法使其与外部工作簿中的按钮一起使用,并且不确定何时以及如何正确引用。
这是代码,我尝试在顶部插入一行,插入Column函数并将其拖动到末尾:
Private Sub CommandButton1_Click()
Dim lastColumn As Integer
Dim rng_source As Range
Dim rng_Destination As Range
Dim l_SourceRows As Long
Set ws = Workbooks("TEST")
ws.Activate
ActiveSheet.Name = "Sheet1"
' Insert row and formula
ws.Worksheets("LV").Activate
ws.Sheets("LV").Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
ws.Sheets("LV").Range("A1").Select
ActiveCell.FormulaR1C1 = "=COLUMN(C)"
' Drag formula until last column
Set rng_source = ws.Sheets("LV").Range("A1")
l_SourceRows = rng_source.Rows.Count
lastColumn = ws.Sheets("LV").Cells(2, Columns.Count).End(xlToLeft).Column
Set rng_Destination = ws.Sheets("LV").Range(rng_source.Cells(1), Cells(rng_source.Cells(1), lastColumn))
rng_source.AutoFill Destination:=rng_Destination, Type:=xlFillDefault
End Sub
非常感谢。
现在暂时不处理其余代码,以下操作是,将“ ws”设置为名为“ TEST”的工作簿(我认为它必须已经打开)。然后,您激活它,并在名称“ Sheet1”上给出您所使用的表。之后,您可以在该“测试”工作表中激活工作表“ LV”。我不确定您要使用这些步骤做什么?
Set ws = Workbooks("TEST")
ws.Activate
ActiveSheet.Name = "Sheet1"
' Insert row and formula
ws.Worksheets("LV").Activate
ws.Sheets("LV").Rows("1:1").Select
我假设您想按一个按钮,打开另一张纸,然后在该纸上输入代码?您如何简单地复制整个代码,创建一个新的子控件,然后将设置行更改为可以打开另一个工作簿的内容呢?也许是这样:
Sub test()
Dim lastColumn As Integer
Dim rng_source As Range
Dim rng_Destination As Range
Dim l_SourceRows As Long
'Filepath of the file in some cell on the workbook (Pick one)
FilePath = ThisWorkbook.Sheets("NameOfTheSheet").Range("B2").Value
'Filepath of the file hard coded in here, simply copy the path and name (Pick one)
FilePath = "C:\Users\TheMan\Desktop\Test.xlsx"
'Open the file
Set ws = Workbooks.Open(FilePath, ReadOnly:=False)
'Now you do everything with the other workbook that you did to "ws" before.
'Not sure you really need/want this.
ws.Activate
ActiveSheet.Name = "Sheet1"
' Insert row and formula
ws.Worksheets("LV").Activate
ws.Sheets("LV").Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
ws.Sheets("LV").Range("A1").Select
ActiveCell.FormulaR1C1 = "=COLUMN(C)"
' Drag formula until last column
Set rng_source = ws.Sheets("LV").Range("A1")
l_SourceRows = rng_source.Rows.Count
lastColumn = ws.Sheets("LV").Cells(2, Columns.Count).End(xlToLeft).Column
Set rng_Destination = ws.Sheets("LV").Range(rng_source.Cells(1), Cells(rng_source.Cells(1), lastColumn))
rng_source.AutoFill Destination:=rng_Destination, Type:=xlFillDefault
End Sub
我没有测试或调整您的任何代码。